1 /*
2  *  Catch v2.9.2
3  *  Generated: 2019-08-08 13:35:12.279703
4  *  ----------------------------------------------------------
5  *  This file has been merged from multiple headers. Please don't edit it directly
6  *  Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved.
7  *
8  *  Distributed under the Boost Software License, Version 1.0. (See accompanying
9  *  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
10  */
11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13 // start catch.hpp
14 
15 
16 #define CATCH_VERSION_MAJOR 2
17 #define CATCH_VERSION_MINOR 9
18 #define CATCH_VERSION_PATCH 2
19 
20 #ifdef __clang__
21 #    pragma clang system_header
22 #elif defined __GNUC__
23 #    pragma GCC system_header
24 #endif
25 
26 // start catch_suppress_warnings.h
27 
28 #ifdef __clang__
29 #   ifdef __ICC // icpc defines the __clang__ macro
30 #       pragma warning(push)
31 #       pragma warning(disable: 161 1682)
32 #   else // __ICC
33 #       pragma clang diagnostic push
34 #       pragma clang diagnostic ignored "-Wpadded"
35 #       pragma clang diagnostic ignored "-Wswitch-enum"
36 #       pragma clang diagnostic ignored "-Wcovered-switch-default"
37 #    endif
38 #elif defined __GNUC__
39      // Because REQUIREs trigger GCC's -Wparentheses, and because still
40      // supported version of g++ have only buggy support for _Pragmas,
41      // Wparentheses have to be suppressed globally.
42 #    pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
43 
44 #    pragma GCC diagnostic push
45 #    pragma GCC diagnostic ignored "-Wunused-variable"
46 #    pragma GCC diagnostic ignored "-Wpadded"
47 #endif
48 // end catch_suppress_warnings.h
49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
50 #  define CATCH_IMPL
51 #  define CATCH_CONFIG_ALL_PARTS
52 #endif
53 
54 // In the impl file, we want to have access to all parts of the headers
55 // Can also be used to sanely support PCHs
56 #if defined(CATCH_CONFIG_ALL_PARTS)
57 #  define CATCH_CONFIG_EXTERNAL_INTERFACES
58 #  if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59 #    undef CATCH_CONFIG_DISABLE_MATCHERS
60 #  endif
61 #  if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62 #    define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
63 #  endif
64 #endif
65 
66 #if !defined(CATCH_CONFIG_IMPL_ONLY)
67 // start catch_platform.h
68 
69 #ifdef __APPLE__
70 # include <TargetConditionals.h>
71 # if TARGET_OS_OSX == 1
72 #  define CATCH_PLATFORM_MAC
73 # elif TARGET_OS_IPHONE == 1
74 #  define CATCH_PLATFORM_IPHONE
75 # endif
76 
77 #elif defined(linux) || defined(__linux) || defined(__linux__)
78 #  define CATCH_PLATFORM_LINUX
79 
80 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
81 #  define CATCH_PLATFORM_WINDOWS
82 #endif
83 
84 // end catch_platform.h
85 
86 #ifdef CATCH_IMPL
87 #  ifndef CLARA_CONFIG_MAIN
88 #    define CLARA_CONFIG_MAIN_NOT_DEFINED
89 #    define CLARA_CONFIG_MAIN
90 #  endif
91 #endif
92 
93 // start catch_user_interfaces.h
94 
95 namespace Catch {
96     unsigned int rngSeed();
97 }
98 
99 // end catch_user_interfaces.h
100 // start catch_tag_alias_autoregistrar.h
101 
102 // start catch_common.h
103 
104 // start catch_compiler_capabilities.h
105 
106 // Detect a number of compiler features - by compiler
107 // The following features are defined:
108 //
109 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
110 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
111 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
112 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
113 // ****************
114 // Note to maintainers: if new toggles are added please document them
115 // in configuration.md, too
116 // ****************
117 
118 // In general each macro has a _NO_<feature name> form
119 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
120 // Many features, at point of detection, define an _INTERNAL_ macro, so they
121 // can be combined, en-mass, with the _NO_ forms later.
122 
123 #ifdef __cplusplus
124 
125 #  if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
126 #    define CATCH_CPP14_OR_GREATER
127 #  endif
128 
129 #  if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
130 #    define CATCH_CPP17_OR_GREATER
131 #  endif
132 
133 #endif
134 
135 #if defined(CATCH_CPP17_OR_GREATER)
136 #  define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
137 #endif
138 
139 #ifdef __clang__
140 
141 #       define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
142             _Pragma( "clang diagnostic push" ) \
143             _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
144             _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
145 #       define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
146             _Pragma( "clang diagnostic pop" )
147 
148 #       define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
149             _Pragma( "clang diagnostic push" ) \
150             _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
151 #       define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
152             _Pragma( "clang diagnostic pop" )
153 
154 #       define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
155             _Pragma( "clang diagnostic push" ) \
156             _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
157 #       define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
158             _Pragma( "clang diagnostic pop" )
159 
160 #       define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
161             _Pragma( "clang diagnostic push" ) \
162             _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
163 #       define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
164             _Pragma( "clang diagnostic pop" )
165 
166 #endif // __clang__
167 
168 ////////////////////////////////////////////////////////////////////////////////
169 // Assume that non-Windows platforms support posix signals by default
170 #if !defined(CATCH_PLATFORM_WINDOWS)
171     #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
172 #endif
173 
174 ////////////////////////////////////////////////////////////////////////////////
175 // We know some environments not to support full POSIX signals
176 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
177     #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
178 #endif
179 
180 #ifdef __OS400__
181 #       define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
182 #       define CATCH_CONFIG_COLOUR_NONE
183 #endif
184 
185 ////////////////////////////////////////////////////////////////////////////////
186 // Android somehow still does not support std::to_string
187 #if defined(__ANDROID__)
188 #    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
189 #endif
190 
191 ////////////////////////////////////////////////////////////////////////////////
192 // Not all Windows environments support SEH properly
193 #if defined(__MINGW32__)
194 #    define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
195 #endif
196 
197 ////////////////////////////////////////////////////////////////////////////////
198 // PS4
199 #if defined(__ORBIS__)
200 #    define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
201 #endif
202 
203 ////////////////////////////////////////////////////////////////////////////////
204 // Cygwin
205 #ifdef __CYGWIN__
206 
207 // Required for some versions of Cygwin to declare gettimeofday
208 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
209 #   define _BSD_SOURCE
210 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
211 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
212 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
213            && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
214 
215 #    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
216 
217 # endif
218 #endif // __CYGWIN__
219 
220 ////////////////////////////////////////////////////////////////////////////////
221 // Visual C++
222 #ifdef _MSC_VER
223 
224 #  if _MSC_VER >= 1900 // Visual Studio 2015 or newer
225 #    define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
226 #  endif
227 
228 // Universal Windows platform does not support SEH
229 // Or console colours (or console at all...)
230 #  if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
231 #    define CATCH_CONFIG_COLOUR_NONE
232 #  else
233 #    define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
234 #  endif
235 
236 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
237 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
238 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
239 #  if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
240 #    define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
241 #  endif
242 #endif // _MSC_VER
243 
244 #if defined(_REENTRANT) || defined(_MSC_VER)
245 // Enable async processing, as -pthread is specified or no additional linking is required
246 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
247 #endif // _MSC_VER
248 
249 ////////////////////////////////////////////////////////////////////////////////
250 // Check if we are compiled with -fno-exceptions or equivalent
251 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
252 #  define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
253 #endif
254 
255 ////////////////////////////////////////////////////////////////////////////////
256 // DJGPP
257 #ifdef __DJGPP__
258 #  define CATCH_INTERNAL_CONFIG_NO_WCHAR
259 #endif // __DJGPP__
260 
261 ////////////////////////////////////////////////////////////////////////////////
262 // Embarcadero C++Build
263 #if defined(__BORLANDC__)
264     #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
265 #endif
266 
267 ////////////////////////////////////////////////////////////////////////////////
268 
269 // Use of __COUNTER__ is suppressed during code analysis in
270 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
271 // handled by it.
272 // Otherwise all supported compilers support COUNTER macro,
273 // but user still might want to turn it off
274 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
275     #define CATCH_INTERNAL_CONFIG_COUNTER
276 #endif
277 
278 ////////////////////////////////////////////////////////////////////////////////
279 
280 // RTX is a special version of Windows that is real time.
281 // This means that it is detected as Windows, but does not provide
282 // the same set of capabilities as real Windows does.
283 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
284     #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
285     #define CATCH_INTERNAL_CONFIG_NO_ASYNC
286     #define CATCH_CONFIG_COLOUR_NONE
287 #endif
288 
289 ////////////////////////////////////////////////////////////////////////////////
290 // Check if string_view is available and usable
291 // The check is split apart to work around v140 (VS2015) preprocessor issue...
292 #if defined(__has_include)
293 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
294 #    define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
295 #endif
296 #endif
297 
298 ////////////////////////////////////////////////////////////////////////////////
299 // Check if optional is available and usable
300 #if defined(__has_include)
301 #  if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
302 #    define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
303 #  endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
304 #endif // __has_include
305 
306 ////////////////////////////////////////////////////////////////////////////////
307 // Check if byte is available and usable
308 #if defined(__has_include)
309 #  if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
310 #    define CATCH_INTERNAL_CONFIG_CPP17_BYTE
311 #  endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
312 #endif // __has_include
313 
314 ////////////////////////////////////////////////////////////////////////////////
315 // Check if variant is available and usable
316 #if defined(__has_include)
317 #  if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
318 #    if defined(__clang__) && (__clang_major__ < 8)
319        // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
320        // fix should be in clang 8, workaround in libstdc++ 8.2
321 #      include <ciso646>
322 #      if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
323 #        define CATCH_CONFIG_NO_CPP17_VARIANT
324 #      else
325 #        define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
326 #      endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
327 #    else
328 #      define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
329 #    endif // defined(__clang__) && (__clang_major__ < 8)
330 #  endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
331 #endif // __has_include
332 
333 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
334 #   define CATCH_CONFIG_COUNTER
335 #endif
336 #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)
337 #   define CATCH_CONFIG_WINDOWS_SEH
338 #endif
339 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
340 #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)
341 #   define CATCH_CONFIG_POSIX_SIGNALS
342 #endif
343 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
344 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
345 #   define CATCH_CONFIG_WCHAR
346 #endif
347 
348 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
349 #    define CATCH_CONFIG_CPP11_TO_STRING
350 #endif
351 
352 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
353 #  define CATCH_CONFIG_CPP17_OPTIONAL
354 #endif
355 
356 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
357 #  define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
358 #endif
359 
360 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
361 #  define CATCH_CONFIG_CPP17_STRING_VIEW
362 #endif
363 
364 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
365 #  define CATCH_CONFIG_CPP17_VARIANT
366 #endif
367 
368 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
369 #  define CATCH_CONFIG_CPP17_BYTE
370 #endif
371 
372 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
373 #  define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
374 #endif
375 
376 #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)
377 #  define CATCH_CONFIG_NEW_CAPTURE
378 #endif
379 
380 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
381 #  define CATCH_CONFIG_DISABLE_EXCEPTIONS
382 #endif
383 
384 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
385 #  define CATCH_CONFIG_POLYFILL_ISNAN
386 #endif
387 
388 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC)  && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
389 #  define CATCH_CONFIG_USE_ASYNC
390 #endif
391 
392 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
393 #   define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
394 #   define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
395 #endif
396 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
397 #   define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
398 #   define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
399 #endif
400 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
401 #   define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
402 #   define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
403 #endif
404 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
405 #   define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
406 #   define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
407 #endif
408 
409 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
410 #define CATCH_TRY if ((true))
411 #define CATCH_CATCH_ALL if ((false))
412 #define CATCH_CATCH_ANON(type) if ((false))
413 #else
414 #define CATCH_TRY try
415 #define CATCH_CATCH_ALL catch (...)
416 #define CATCH_CATCH_ANON(type) catch (type)
417 #endif
418 
419 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
420 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
421 #endif
422 
423 // end catch_compiler_capabilities.h
424 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
425 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
426 #ifdef CATCH_CONFIG_COUNTER
427 #  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
428 #else
429 #  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
430 #endif
431 
432 #include <iosfwd>
433 #include <string>
434 #include <cstdint>
435 
436 // We need a dummy global operator<< so we can bring it into Catch namespace later
437 struct Catch_global_namespace_dummy {};
438 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
439 
440 namespace Catch {
441 
442     struct CaseSensitive { enum Choice {
443         Yes,
444         No
445     }; };
446 
447     class NonCopyable {
448         NonCopyable( NonCopyable const& )              = delete;
449         NonCopyable( NonCopyable && )                  = delete;
450         NonCopyable& operator = ( NonCopyable const& ) = delete;
451         NonCopyable& operator = ( NonCopyable && )     = delete;
452 
453     protected:
454         NonCopyable();
455         virtual ~NonCopyable();
456     };
457 
458     struct SourceLineInfo {
459 
460         SourceLineInfo() = delete;
SourceLineInfoCatch::SourceLineInfo461         SourceLineInfo( char const* _file, std::size_t _line ) noexcept
462         :   file( _file ),
463             line( _line )
464         {}
465 
466         SourceLineInfo( SourceLineInfo const& other )            = default;
467         SourceLineInfo& operator = ( SourceLineInfo const& )     = default;
468         SourceLineInfo( SourceLineInfo&& )              noexcept = default;
469         SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
470 
471         bool empty() const noexcept;
472         bool operator == ( SourceLineInfo const& other ) const noexcept;
473         bool operator < ( SourceLineInfo const& other ) const noexcept;
474 
475         char const* file;
476         std::size_t line;
477     };
478 
479     std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
480 
481     // Bring in operator<< from global namespace into Catch namespace
482     // This is necessary because the overload of operator<< above makes
483     // lookup stop at namespace Catch
484     using ::operator<<;
485 
486     // Use this in variadic streaming macros to allow
487     //    >> +StreamEndStop
488     // as well as
489     //    >> stuff +StreamEndStop
490     struct StreamEndStop {
491         std::string operator+() const;
492     };
493     template<typename T>
operator +(T const & value,StreamEndStop)494     T const& operator + ( T const& value, StreamEndStop ) {
495         return value;
496     }
497 }
498 
499 #define CATCH_INTERNAL_LINEINFO \
500     ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
501 
502 // end catch_common.h
503 namespace Catch {
504 
505     struct RegistrarForTagAliases {
506         RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
507     };
508 
509 } // end namespace Catch
510 
511 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
512     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
513     namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
514     CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
515 
516 // end catch_tag_alias_autoregistrar.h
517 // start catch_test_registry.h
518 
519 // start catch_interfaces_testcase.h
520 
521 #include <vector>
522 
523 namespace Catch {
524 
525     class TestSpec;
526 
527     struct ITestInvoker {
528         virtual void invoke () const = 0;
529         virtual ~ITestInvoker();
530     };
531 
532     class TestCase;
533     struct IConfig;
534 
535     struct ITestCaseRegistry {
536         virtual ~ITestCaseRegistry();
537         virtual std::vector<TestCase> const& getAllTests() const = 0;
538         virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
539     };
540 
541     bool isThrowSafe( TestCase const& testCase, IConfig const& config );
542     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
543     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
544     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
545 
546 }
547 
548 // end catch_interfaces_testcase.h
549 // start catch_stringref.h
550 
551 #include <cstddef>
552 #include <string>
553 #include <iosfwd>
554 
555 namespace Catch {
556 
557     /// A non-owning string class (similar to the forthcoming std::string_view)
558     /// Note that, because a StringRef may be a substring of another string,
559     /// it may not be null terminated. c_str() must return a null terminated
560     /// string, however, and so the StringRef will internally take ownership
561     /// (taking a copy), if necessary. In theory this ownership is not externally
562     /// visible - but it does mean (substring) StringRefs should not be shared between
563     /// threads.
564     class StringRef {
565     public:
566         using size_type = std::size_t;
567 
568     private:
569         friend struct StringRefTestAccess;
570 
571         char const* m_start;
572         size_type m_size;
573 
574         char* m_data = nullptr;
575 
576         void takeOwnership();
577 
578         static constexpr char const* const s_empty = "";
579 
580     public: // construction/ assignment
StringRef()581         StringRef() noexcept
582         :   StringRef( s_empty, 0 )
583         {}
584 
StringRef(StringRef const & other)585         StringRef( StringRef const& other ) noexcept
586         :   m_start( other.m_start ),
587             m_size( other.m_size )
588         {}
589 
StringRef(StringRef && other)590         StringRef( StringRef&& other ) noexcept
591         :   m_start( other.m_start ),
592             m_size( other.m_size ),
593             m_data( other.m_data )
594         {
595             other.m_data = nullptr;
596         }
597 
598         StringRef( char const* rawChars ) noexcept;
599 
StringRef(char const * rawChars,size_type size)600         StringRef( char const* rawChars, size_type size ) noexcept
601         :   m_start( rawChars ),
602             m_size( size )
603         {}
604 
StringRef(std::string const & stdString)605         StringRef( std::string const& stdString ) noexcept
606         :   m_start( stdString.c_str() ),
607             m_size( stdString.size() )
608         {}
609 
~StringRef()610         ~StringRef() noexcept {
611             delete[] m_data;
612         }
613 
operator =(StringRef const & other)614         auto operator = ( StringRef const &other ) noexcept -> StringRef& {
615             delete[] m_data;
616             m_data = nullptr;
617             m_start = other.m_start;
618             m_size = other.m_size;
619             return *this;
620         }
621 
622         operator std::string() const;
623 
624         void swap( StringRef& other ) noexcept;
625 
626     public: // operators
627         auto operator == ( StringRef const& other ) const noexcept -> bool;
628         auto operator != ( StringRef const& other ) const noexcept -> bool;
629 
630         auto operator[] ( size_type index ) const noexcept -> char;
631 
632     public: // named queries
empty() const633         auto empty() const noexcept -> bool {
634             return m_size == 0;
635         }
size() const636         auto size() const noexcept -> size_type {
637             return m_size;
638         }
639 
640         auto numberOfCharacters() const noexcept -> size_type;
641         auto c_str() const -> char const*;
642 
643     public: // substrings and searches
644         auto substr( size_type start, size_type size ) const noexcept -> StringRef;
645 
646         // Returns the current start pointer.
647         // Note that the pointer can change when if the StringRef is a substring
648         auto currentData() const noexcept -> char const*;
649 
650     private: // ownership queries - may not be consistent between calls
651         auto isOwned() const noexcept -> bool;
652         auto isSubstring() const noexcept -> bool;
653     };
654 
655     auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
656     auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
657     auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
658 
659     auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
660     auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
661 
operator ""_sr(char const * rawChars,std::size_t size)662     inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
663         return StringRef( rawChars, size );
664     }
665 
666 } // namespace Catch
667 
operator ""_catch_sr(char const * rawChars,std::size_t size)668 inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
669     return Catch::StringRef( rawChars, size );
670 }
671 
672 // end catch_stringref.h
673 // start catch_type_traits.hpp
674 
675 
676 #include <type_traits>
677 
678 namespace Catch{
679 
680 #ifdef CATCH_CPP17_OR_GREATER
681 	template <typename...>
682 	inline constexpr auto is_unique = std::true_type{};
683 
684 	template <typename T, typename... Rest>
685 	inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
686 		(!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
687 	>{};
688 #else
689 
690 template <typename...>
691 struct is_unique : std::true_type{};
692 
693 template <typename T0, typename T1, typename... Rest>
694 struct is_unique<T0, T1, Rest...> : std::integral_constant
695 <bool,
696      !std::is_same<T0, T1>::value
697      && is_unique<T0, Rest...>::value
698      && is_unique<T1, Rest...>::value
699 >{};
700 
701 #endif
702 }
703 
704 // end catch_type_traits.hpp
705 // start catch_preprocessor.hpp
706 
707 
708 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
709 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
710 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
711 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
712 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
713 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
714 
715 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
716 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
717 // MSVC needs more evaluations
718 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
719 #define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
720 #else
721 #define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL5(__VA_ARGS__)
722 #endif
723 
724 #define CATCH_REC_END(...)
725 #define CATCH_REC_OUT
726 
727 #define CATCH_EMPTY()
728 #define CATCH_DEFER(id) id CATCH_EMPTY()
729 
730 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
731 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
732 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
733 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
734 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
735 #define CATCH_REC_NEXT(test, next)  CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
736 
737 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
738 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
739 #define CATCH_REC_LIST2(f, x, peek, ...)   f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
740 
741 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
742 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
743 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...)   f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
744 
745 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
746 // and passes userdata as the first parameter to each invocation,
747 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
748 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
749 
750 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
751 
752 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
753 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
754 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
755 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
756 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
757 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
758 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
759 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
760 #else
761 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
762 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
763 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
764 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
765 #endif
766 
767 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
768 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
769 
770 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
771 
772 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
773 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
774 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
775 #else
776 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
777 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
778 #endif
779 
780 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
781     CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
782 
783 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
784 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
785 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
786 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
787 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
788 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
789 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _4, _5, _6)
790 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
791 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
792 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
793 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
794 
795 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
796 
797 #define INTERNAL_CATCH_TYPE_GEN\
798     template<typename...> struct TypeList {};\
799     template<typename...Ts>\
800     constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
801     \
802     template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
803     constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
804     template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
805     constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
806     template< template<typename...> class L1, typename...E1, typename...Rest>\
807     constexpr auto append(L1<E1...>, TypeList<mpl_::na>, Rest...) noexcept -> L1<E1...> { return {}; }\
808     \
809     template< template<typename...> class Container, template<typename...> class List, typename...elems>\
810     constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
811     template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
812     constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
813     \
814     template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
815     constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }\
816     template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
817     constexpr auto convert(List<Ts...>) noexcept -> decltype(append(Final<>{},TypeList<Ts>{}...)) { return {}; }
818 
819 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
820     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
821     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
822     constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
823     \
824     template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
825     constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
826     template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
827     constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
828     template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
829     constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
830 
831 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
832 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
833     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834     static void TestName()
835 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
836     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
837     static void TestName()
838 
839 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
840 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
841     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
842     static void TestName()
843 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
844     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
845     static void TestName()
846 
847 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
848     template<typename Type>\
849     void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
850     {\
851         Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
852     }
853 
854 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
855     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
856     void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
857     {\
858         Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
859     }
860 
861 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
862     template<typename Type>\
863     void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
864     {\
865         Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
866     }
867 
868 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
869     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
870     void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
871     {\
872         Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
873     }
874 
875 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
876 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
877     template<typename TestType> \
878     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
879         void test();\
880     }
881 
882 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
883     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
884     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
885         void test();\
886     }
887 
888 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
890     template<typename TestType> \
891     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
892 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
893     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
894     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
895 
896 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
897 #define INTERNAL_CATCH_NTTP_0
898 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
899 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
900 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
901 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
902 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
903 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
904 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
905 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
906 #else
907 #define INTERNAL_CATCH_NTTP_0(signature)
908 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
909 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
910 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
911 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
912 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
913 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
914 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
915 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
916 #endif
917 
918 // end catch_preprocessor.hpp
919 // start catch_meta.hpp
920 
921 
922 #include <type_traits>
923 
924 namespace Catch {
925 template<typename T>
926 struct always_false : std::false_type {};
927 
928 template <typename> struct true_given : std::true_type {};
929 struct is_callable_tester {
930     template <typename Fun, typename... Args>
931     true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
932     template <typename...>
933     std::false_type static test(...);
934 };
935 
936 template <typename T>
937 struct is_callable;
938 
939 template <typename Fun, typename... Args>
940 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
941 
942 } // namespace Catch
943 
944 namespace mpl_{
945     struct na;
946 }
947 
948 // end catch_meta.hpp
949 namespace Catch {
950 
951 template<typename C>
952 class TestInvokerAsMethod : public ITestInvoker {
953     void (C::*m_testAsMethod)();
954 public:
TestInvokerAsMethod(void (C::* testAsMethod)())955     TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
956 
invoke() const957     void invoke() const override {
958         C obj;
959         (obj.*m_testAsMethod)();
960     }
961 };
962 
963 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
964 
965 template<typename C>
makeTestInvoker(void (C::* testAsMethod)())966 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
967     return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
968 }
969 
970 struct NameAndTags {
971     NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
972     StringRef name;
973     StringRef tags;
974 };
975 
976 struct AutoReg : NonCopyable {
977     AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
978     ~AutoReg();
979 };
980 
981 } // end namespace Catch
982 
983 #if defined(CATCH_CONFIG_DISABLE)
984     #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
985         static void TestName()
986     #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
987         namespace{                        \
988             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
989                 void test();              \
990             };                            \
991         }                                 \
992         void TestName::test()
993     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... )  \
994         INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
995     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... )    \
996         namespace{                                                                                  \
997             namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                      \
998             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
999         }                                                                                           \
1000         }                                                                                           \
1001         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1002 
1003     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1004         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1005             INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1006     #else
1007         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1008             INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1009     #endif
1010 
1011     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1012         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1013             INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1014     #else
1015         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1016             INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1017     #endif
1018 
1019     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1020         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1021             INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1022     #else
1023         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1024             INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1025     #endif
1026 
1027     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1028         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1029             INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1030     #else
1031         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1032             INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1033     #endif
1034 #endif
1035 
1036     ///////////////////////////////////////////////////////////////////////////////
1037     #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1038         static void TestName(); \
1039         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1040         namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1041         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1042         static void TestName()
1043     #define INTERNAL_CATCH_TESTCASE( ... ) \
1044         INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1045 
1046     ///////////////////////////////////////////////////////////////////////////////
1047     #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1048         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1049         namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1050         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
1051 
1052     ///////////////////////////////////////////////////////////////////////////////
1053     #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1054         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1055         namespace{ \
1056             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1057                 void test(); \
1058             }; \
1059             Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1060         } \
1061         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1062         void TestName::test()
1063     #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1064         INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1065 
1066     ///////////////////////////////////////////////////////////////////////////////
1067     #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1068         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1069         Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1070         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
1071 
1072     ///////////////////////////////////////////////////////////////////////////////
1073     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1074         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1075         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1076         INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1077         namespace {\
1078         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1079             INTERNAL_CATCH_TYPE_GEN\
1080             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1081             INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1082             template<typename...Types> \
1083             struct TestName{\
1084                 TestName(){\
1085                     int index = 0;                                    \
1086                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1087                     using expander = int[];\
1088                     (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1089                 }\
1090             };\
1091             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1092             TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1093             return 0;\
1094         }();\
1095         }\
1096         }\
1097         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1098         CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1099         INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1100 
1101 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1102     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1103         INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1104 #else
1105     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1106         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1107 #endif
1108 
1109 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1110     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1111         INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1112 #else
1113     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1114         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1115 #endif
1116 
1117     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1118         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                      \
1119         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                \
1120         template<typename TestType> static void TestFuncName();       \
1121         namespace {\
1122         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                     \
1123             INTERNAL_CATCH_TYPE_GEN                                                  \
1124             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))         \
1125             template<typename... Types>                               \
1126             struct TestName {                                         \
1127                 void reg_tests() {                                          \
1128                     int index = 0;                                    \
1129                     using expander = int[];                           \
1130                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1131                     constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1132                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1133                     (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\
1134                 }                                                     \
1135             };                                                        \
1136             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1137                 using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
1138                 TestInit t;                                           \
1139                 t.reg_tests();                                        \
1140                 return 0;                                             \
1141             }();                                                      \
1142         }                                                             \
1143         }                                                             \
1144         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS                    \
1145         CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS              \
1146         template<typename TestType>                                   \
1147         static void TestFuncName()
1148 
1149 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1150     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1151         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
1152 #else
1153     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1154         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
1155 #endif
1156 
1157 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1158     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1159         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
1160 #else
1161     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1162         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1163 #endif
1164 
1165     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1166         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1167         template<typename TestType> static void TestFunc();       \
1168         namespace {\
1169         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1170         INTERNAL_CATCH_TYPE_GEN\
1171         template<typename... Types>                               \
1172         struct TestName {                                         \
1173             void reg_tests() {                                          \
1174                 int index = 0;                                    \
1175                 using expander = int[];                           \
1176                 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */\
1177             }                                                     \
1178         };\
1179         static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1180                 using TestInit = decltype(convert<TestName>(std::declval<TmplList>())); \
1181                 TestInit t;                                           \
1182                 t.reg_tests();                                        \
1183                 return 0;                                             \
1184             }();                                                        \
1185         }}\
1186         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS                    \
1187         template<typename TestType>                                   \
1188         static void TestFunc()
1189 
1190     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1191         INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
1192 
1193     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1194         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1195         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1196         namespace {\
1197         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1198             INTERNAL_CATCH_TYPE_GEN\
1199             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1200             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1201             INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1202             template<typename...Types> \
1203             struct TestNameClass{\
1204                 TestNameClass(){\
1205                     int index = 0;                                    \
1206                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1207                     using expander = int[];\
1208                     (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1209                 }\
1210             };\
1211             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1212                 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1213                 return 0;\
1214         }();\
1215         }\
1216         }\
1217         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
1218         CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
1219         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1220 
1221 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1222     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1223         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1224 #else
1225     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1226         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1227 #endif
1228 
1229 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1230     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1231         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1232 #else
1233     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1234         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1235 #endif
1236 
1237     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1238         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1239         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1240         template<typename TestType> \
1241             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1242                 void test();\
1243             };\
1244         namespace {\
1245         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1246             INTERNAL_CATCH_TYPE_GEN                  \
1247             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1248             template<typename...Types>\
1249             struct TestNameClass{\
1250                 void reg_tests(){\
1251                     int index = 0;\
1252                     using expander = int[];\
1253                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1254                     constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1255                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1256                     (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \
1257                 }\
1258             };\
1259             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1260                 using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
1261                 TestInit t;\
1262                 t.reg_tests();\
1263                 return 0;\
1264             }(); \
1265         }\
1266         }\
1267         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1268         CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1269         template<typename TestType> \
1270         void TestName<TestType>::test()
1271 
1272 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1273     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1274         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1275 #else
1276     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1277         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1278 #endif
1279 
1280 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1281     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1282         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1283 #else
1284     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1285         INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1286 #endif
1287 
1288     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1289         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1290         template<typename TestType> \
1291         struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1292             void test();\
1293         };\
1294         namespace {\
1295         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1296             INTERNAL_CATCH_TYPE_GEN\
1297             template<typename...Types>\
1298             struct TestNameClass{\
1299                 void reg_tests(){\
1300                     int index = 0;\
1301                     using expander = int[];\
1302                     (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++, 0)... };/* NOLINT */ \
1303                 }\
1304             };\
1305             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1306                 using TestInit = decltype(convert<TestNameClass>(std::declval<TmplList>()));\
1307                 TestInit t;\
1308                 t.reg_tests();\
1309                 return 0;\
1310             }(); \
1311         }}\
1312         CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1313         template<typename TestType> \
1314         void TestName<TestType>::test()
1315 
1316 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1317         INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
1318 
1319 // end catch_test_registry.h
1320 // start catch_capture.hpp
1321 
1322 // start catch_assertionhandler.h
1323 
1324 // start catch_assertioninfo.h
1325 
1326 // start catch_result_type.h
1327 
1328 namespace Catch {
1329 
1330     // ResultWas::OfType enum
1331     struct ResultWas { enum OfType {
1332         Unknown = -1,
1333         Ok = 0,
1334         Info = 1,
1335         Warning = 2,
1336 
1337         FailureBit = 0x10,
1338 
1339         ExpressionFailed = FailureBit | 1,
1340         ExplicitFailure = FailureBit | 2,
1341 
1342         Exception = 0x100 | FailureBit,
1343 
1344         ThrewException = Exception | 1,
1345         DidntThrowException = Exception | 2,
1346 
1347         FatalErrorCondition = 0x200 | FailureBit
1348 
1349     }; };
1350 
1351     bool isOk( ResultWas::OfType resultType );
1352     bool isJustInfo( int flags );
1353 
1354     // ResultDisposition::Flags enum
1355     struct ResultDisposition { enum Flags {
1356         Normal = 0x01,
1357 
1358         ContinueOnFailure = 0x02,   // Failures fail test, but execution continues
1359         FalseTest = 0x04,           // Prefix expression with !
1360         SuppressFail = 0x08         // Failures are reported but do not fail the test
1361     }; };
1362 
1363     ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1364 
1365     bool shouldContinueOnFailure( int flags );
isFalseTest(int flags)1366     inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1367     bool shouldSuppressFailure( int flags );
1368 
1369 } // end namespace Catch
1370 
1371 // end catch_result_type.h
1372 namespace Catch {
1373 
1374     struct AssertionInfo
1375     {
1376         StringRef macroName;
1377         SourceLineInfo lineInfo;
1378         StringRef capturedExpression;
1379         ResultDisposition::Flags resultDisposition;
1380 
1381         // We want to delete this constructor but a compiler bug in 4.8 means
1382         // the struct is then treated as non-aggregate
1383         //AssertionInfo() = delete;
1384     };
1385 
1386 } // end namespace Catch
1387 
1388 // end catch_assertioninfo.h
1389 // start catch_decomposer.h
1390 
1391 // start catch_tostring.h
1392 
1393 #include <vector>
1394 #include <cstddef>
1395 #include <type_traits>
1396 #include <string>
1397 // start catch_stream.h
1398 
1399 #include <iosfwd>
1400 #include <cstddef>
1401 #include <ostream>
1402 
1403 namespace Catch {
1404 
1405     std::ostream& cout();
1406     std::ostream& cerr();
1407     std::ostream& clog();
1408 
1409     class StringRef;
1410 
1411     struct IStream {
1412         virtual ~IStream();
1413         virtual std::ostream& stream() const = 0;
1414     };
1415 
1416     auto makeStream( StringRef const &filename ) -> IStream const*;
1417 
1418     class ReusableStringStream {
1419         std::size_t m_index;
1420         std::ostream* m_oss;
1421     public:
1422         ReusableStringStream();
1423         ~ReusableStringStream();
1424 
1425         auto str() const -> std::string;
1426 
1427         template<typename T>
operator <<(T const & value)1428         auto operator << ( T const& value ) -> ReusableStringStream& {
1429             *m_oss << value;
1430             return *this;
1431         }
get()1432         auto get() -> std::ostream& { return *m_oss; }
1433     };
1434 }
1435 
1436 // end catch_stream.h
1437 // start catch_interfaces_enum_values_registry.h
1438 
1439 #include <vector>
1440 
1441 namespace Catch {
1442 
1443     namespace Detail {
1444         struct EnumInfo {
1445             StringRef m_name;
1446             std::vector<std::pair<int, std::string>> m_values;
1447 
1448             ~EnumInfo();
1449 
1450             StringRef lookup( int value ) const;
1451         };
1452     } // namespace Detail
1453 
1454     struct IMutableEnumValuesRegistry {
1455         virtual ~IMutableEnumValuesRegistry();
1456 
1457         virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1458 
1459         template<typename E>
registerEnumCatch::IMutableEnumValuesRegistry1460         Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1461             std::vector<int> intValues;
1462             intValues.reserve( values.size() );
1463             for( auto enumValue : values )
1464                 intValues.push_back( static_cast<int>( enumValue ) );
1465             return registerEnum( enumName, allEnums, intValues );
1466         }
1467     };
1468 
1469 } // Catch
1470 
1471 // end catch_interfaces_enum_values_registry.h
1472 
1473 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1474 #include <string_view>
1475 #endif
1476 
1477 #ifdef __OBJC__
1478 // start catch_objc_arc.hpp
1479 
1480 #import <Foundation/Foundation.h>
1481 
1482 #ifdef __has_feature
1483 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1484 #else
1485 #define CATCH_ARC_ENABLED 0
1486 #endif
1487 
1488 void arcSafeRelease( NSObject* obj );
1489 id performOptionalSelector( id obj, SEL sel );
1490 
1491 #if !CATCH_ARC_ENABLED
arcSafeRelease(NSObject * obj)1492 inline void arcSafeRelease( NSObject* obj ) {
1493     [obj release];
1494 }
performOptionalSelector(id obj,SEL sel)1495 inline id performOptionalSelector( id obj, SEL sel ) {
1496     if( [obj respondsToSelector: sel] )
1497         return [obj performSelector: sel];
1498     return nil;
1499 }
1500 #define CATCH_UNSAFE_UNRETAINED
1501 #define CATCH_ARC_STRONG
1502 #else
arcSafeRelease(NSObject *)1503 inline void arcSafeRelease( NSObject* ){}
performOptionalSelector(id obj,SEL sel)1504 inline id performOptionalSelector( id obj, SEL sel ) {
1505 #ifdef __clang__
1506 #pragma clang diagnostic push
1507 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1508 #endif
1509     if( [obj respondsToSelector: sel] )
1510         return [obj performSelector: sel];
1511 #ifdef __clang__
1512 #pragma clang diagnostic pop
1513 #endif
1514     return nil;
1515 }
1516 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1517 #define CATCH_ARC_STRONG __strong
1518 #endif
1519 
1520 // end catch_objc_arc.hpp
1521 #endif
1522 
1523 #ifdef _MSC_VER
1524 #pragma warning(push)
1525 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1526 #endif
1527 
1528 namespace Catch {
1529     namespace Detail {
1530 
1531         extern const std::string unprintableString;
1532 
1533         std::string rawMemoryToString( const void *object, std::size_t size );
1534 
1535         template<typename T>
rawMemoryToString(const T & object)1536         std::string rawMemoryToString( const T& object ) {
1537           return rawMemoryToString( &object, sizeof(object) );
1538         }
1539 
1540         template<typename T>
1541         class IsStreamInsertable {
1542             template<typename SS, typename TT>
1543             static auto test(int)
1544                 -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
1545 
1546             template<typename, typename>
1547             static auto test(...)->std::false_type;
1548 
1549         public:
1550             static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1551         };
1552 
1553         template<typename E>
1554         std::string convertUnknownEnumToString( E e );
1555 
1556         template<typename T>
1557         typename std::enable_if<
1558             !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const &)1559         std::string>::type convertUnstreamable( T const& ) {
1560             return Detail::unprintableString;
1561         }
1562         template<typename T>
1563         typename std::enable_if<
1564             !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const & ex)1565          std::string>::type convertUnstreamable(T const& ex) {
1566             return ex.what();
1567         }
1568 
1569         template<typename T>
1570         typename std::enable_if<
1571             std::is_enum<T>::value
convertUnstreamable(T const & value)1572         , std::string>::type convertUnstreamable( T const& value ) {
1573             return convertUnknownEnumToString( value );
1574         }
1575 
1576 #if defined(_MANAGED)
1577         //! Convert a CLR string to a utf8 std::string
1578         template<typename T>
1579         std::string clrReferenceToString( T^ ref ) {
1580             if (ref == nullptr)
1581                 return std::string("null");
1582             auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1583             cli::pin_ptr<System::Byte> p = &bytes[0];
1584             return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1585         }
1586 #endif
1587 
1588     } // namespace Detail
1589 
1590     // If we decide for C++14, change these to enable_if_ts
1591     template <typename T, typename = void>
1592     struct StringMaker {
1593         template <typename Fake = T>
1594         static
1595         typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1596             convert(const Fake& value) {
1597                 ReusableStringStream rss;
1598                 // NB: call using the function-like syntax to avoid ambiguity with
1599                 // user-defined templated operator<< under clang.
1600                 rss.operator<<(value);
1601                 return rss.str();
1602         }
1603 
1604         template <typename Fake = T>
1605         static
1606         typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1607             convert( const Fake& value ) {
1608 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1609             return Detail::convertUnstreamable(value);
1610 #else
1611             return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1612 #endif
1613         }
1614     };
1615 
1616     namespace Detail {
1617 
1618         // This function dispatches all stringification requests inside of Catch.
1619         // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1620         template <typename T>
stringify(const T & e)1621         std::string stringify(const T& e) {
1622             return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1623         }
1624 
1625         template<typename E>
convertUnknownEnumToString(E e)1626         std::string convertUnknownEnumToString( E e ) {
1627             return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1628         }
1629 
1630 #if defined(_MANAGED)
1631         template <typename T>
1632         std::string stringify( T^ e ) {
1633             return ::Catch::StringMaker<T^>::convert(e);
1634         }
1635 #endif
1636 
1637     } // namespace Detail
1638 
1639     // Some predefined specializations
1640 
1641     template<>
1642     struct StringMaker<std::string> {
1643         static std::string convert(const std::string& str);
1644     };
1645 
1646 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1647     template<>
1648     struct StringMaker<std::string_view> {
1649         static std::string convert(std::string_view str);
1650     };
1651 #endif
1652 
1653     template<>
1654     struct StringMaker<char const *> {
1655         static std::string convert(char const * str);
1656     };
1657     template<>
1658     struct StringMaker<char *> {
1659         static std::string convert(char * str);
1660     };
1661 
1662 #ifdef CATCH_CONFIG_WCHAR
1663     template<>
1664     struct StringMaker<std::wstring> {
1665         static std::string convert(const std::wstring& wstr);
1666     };
1667 
1668 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1669     template<>
1670     struct StringMaker<std::wstring_view> {
1671         static std::string convert(std::wstring_view str);
1672     };
1673 # endif
1674 
1675     template<>
1676     struct StringMaker<wchar_t const *> {
1677         static std::string convert(wchar_t const * str);
1678     };
1679     template<>
1680     struct StringMaker<wchar_t *> {
1681         static std::string convert(wchar_t * str);
1682     };
1683 #endif
1684 
1685     // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1686     //      while keeping string semantics?
1687     template<int SZ>
1688     struct StringMaker<char[SZ]> {
convertCatch::StringMaker1689         static std::string convert(char const* str) {
1690             return ::Catch::Detail::stringify(std::string{ str });
1691         }
1692     };
1693     template<int SZ>
1694     struct StringMaker<signed char[SZ]> {
convertCatch::StringMaker1695         static std::string convert(signed char const* str) {
1696             return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1697         }
1698     };
1699     template<int SZ>
1700     struct StringMaker<unsigned char[SZ]> {
convertCatch::StringMaker1701         static std::string convert(unsigned char const* str) {
1702             return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1703         }
1704     };
1705 
1706 #if defined(CATCH_CONFIG_CPP17_BYTE)
1707     template<>
1708     struct StringMaker<std::byte> {
1709         static std::string convert(std::byte value);
1710     };
1711 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1712     template<>
1713     struct StringMaker<int> {
1714         static std::string convert(int value);
1715     };
1716     template<>
1717     struct StringMaker<long> {
1718         static std::string convert(long value);
1719     };
1720     template<>
1721     struct StringMaker<long long> {
1722         static std::string convert(long long value);
1723     };
1724     template<>
1725     struct StringMaker<unsigned int> {
1726         static std::string convert(unsigned int value);
1727     };
1728     template<>
1729     struct StringMaker<unsigned long> {
1730         static std::string convert(unsigned long value);
1731     };
1732     template<>
1733     struct StringMaker<unsigned long long> {
1734         static std::string convert(unsigned long long value);
1735     };
1736 
1737     template<>
1738     struct StringMaker<bool> {
1739         static std::string convert(bool b);
1740     };
1741 
1742     template<>
1743     struct StringMaker<char> {
1744         static std::string convert(char c);
1745     };
1746     template<>
1747     struct StringMaker<signed char> {
1748         static std::string convert(signed char c);
1749     };
1750     template<>
1751     struct StringMaker<unsigned char> {
1752         static std::string convert(unsigned char c);
1753     };
1754 
1755     template<>
1756     struct StringMaker<std::nullptr_t> {
1757         static std::string convert(std::nullptr_t);
1758     };
1759 
1760     template<>
1761     struct StringMaker<float> {
1762         static std::string convert(float value);
1763         static int precision;
1764     };
1765 
1766     template<>
1767     struct StringMaker<double> {
1768         static std::string convert(double value);
1769         static int precision;
1770     };
1771 
1772     template <typename T>
1773     struct StringMaker<T*> {
1774         template <typename U>
convertCatch::StringMaker1775         static std::string convert(U* p) {
1776             if (p) {
1777                 return ::Catch::Detail::rawMemoryToString(p);
1778             } else {
1779                 return "nullptr";
1780             }
1781         }
1782     };
1783 
1784     template <typename R, typename C>
1785     struct StringMaker<R C::*> {
convertCatch::StringMaker1786         static std::string convert(R C::* p) {
1787             if (p) {
1788                 return ::Catch::Detail::rawMemoryToString(p);
1789             } else {
1790                 return "nullptr";
1791             }
1792         }
1793     };
1794 
1795 #if defined(_MANAGED)
1796     template <typename T>
1797     struct StringMaker<T^> {
1798         static std::string convert( T^ ref ) {
1799             return ::Catch::Detail::clrReferenceToString(ref);
1800         }
1801     };
1802 #endif
1803 
1804     namespace Detail {
1805         template<typename InputIterator>
rangeToString(InputIterator first,InputIterator last)1806         std::string rangeToString(InputIterator first, InputIterator last) {
1807             ReusableStringStream rss;
1808             rss << "{ ";
1809             if (first != last) {
1810                 rss << ::Catch::Detail::stringify(*first);
1811                 for (++first; first != last; ++first)
1812                     rss << ", " << ::Catch::Detail::stringify(*first);
1813             }
1814             rss << " }";
1815             return rss.str();
1816         }
1817     }
1818 
1819 #ifdef __OBJC__
1820     template<>
1821     struct StringMaker<NSString*> {
convertCatch::StringMaker1822         static std::string convert(NSString * nsstring) {
1823             if (!nsstring)
1824                 return "nil";
1825             return std::string("@") + [nsstring UTF8String];
1826         }
1827     };
1828     template<>
1829     struct StringMaker<NSObject*> {
convertCatch::StringMaker1830         static std::string convert(NSObject* nsObject) {
1831             return ::Catch::Detail::stringify([nsObject description]);
1832         }
1833 
1834     };
1835     namespace Detail {
stringify(NSString * nsstring)1836         inline std::string stringify( NSString* nsstring ) {
1837             return StringMaker<NSString*>::convert( nsstring );
1838         }
1839 
1840     } // namespace Detail
1841 #endif // __OBJC__
1842 
1843 } // namespace Catch
1844 
1845 //////////////////////////////////////////////////////
1846 // Separate std-lib types stringification, so it can be selectively enabled
1847 // This means that we do not bring in
1848 
1849 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1850 #  define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1851 #  define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1852 #  define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1853 #  define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1854 #  define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1855 #endif
1856 
1857 // Separate std::pair specialization
1858 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1859 #include <utility>
1860 namespace Catch {
1861     template<typename T1, typename T2>
1862     struct StringMaker<std::pair<T1, T2> > {
convertCatch::StringMaker1863         static std::string convert(const std::pair<T1, T2>& pair) {
1864             ReusableStringStream rss;
1865             rss << "{ "
1866                 << ::Catch::Detail::stringify(pair.first)
1867                 << ", "
1868                 << ::Catch::Detail::stringify(pair.second)
1869                 << " }";
1870             return rss.str();
1871         }
1872     };
1873 }
1874 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1875 
1876 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1877 #include <optional>
1878 namespace Catch {
1879     template<typename T>
1880     struct StringMaker<std::optional<T> > {
convertCatch::StringMaker1881         static std::string convert(const std::optional<T>& optional) {
1882             ReusableStringStream rss;
1883             if (optional.has_value()) {
1884                 rss << ::Catch::Detail::stringify(*optional);
1885             } else {
1886                 rss << "{ }";
1887             }
1888             return rss.str();
1889         }
1890     };
1891 }
1892 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1893 
1894 // Separate std::tuple specialization
1895 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1896 #include <tuple>
1897 namespace Catch {
1898     namespace Detail {
1899         template<
1900             typename Tuple,
1901             std::size_t N = 0,
1902             bool = (N < std::tuple_size<Tuple>::value)
1903             >
1904             struct TupleElementPrinter {
printCatch::Detail::TupleElementPrinter1905             static void print(const Tuple& tuple, std::ostream& os) {
1906                 os << (N ? ", " : " ")
1907                     << ::Catch::Detail::stringify(std::get<N>(tuple));
1908                 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1909             }
1910         };
1911 
1912         template<
1913             typename Tuple,
1914             std::size_t N
1915         >
1916             struct TupleElementPrinter<Tuple, N, false> {
printCatch::Detail::TupleElementPrinter1917             static void print(const Tuple&, std::ostream&) {}
1918         };
1919 
1920     }
1921 
1922     template<typename ...Types>
1923     struct StringMaker<std::tuple<Types...>> {
convertCatch::StringMaker1924         static std::string convert(const std::tuple<Types...>& tuple) {
1925             ReusableStringStream rss;
1926             rss << '{';
1927             Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1928             rss << " }";
1929             return rss.str();
1930         }
1931     };
1932 }
1933 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1934 
1935 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1936 #include <variant>
1937 namespace Catch {
1938     template<>
1939     struct StringMaker<std::monostate> {
convertCatch::StringMaker1940         static std::string convert(const std::monostate&) {
1941             return "{ }";
1942         }
1943     };
1944 
1945     template<typename... Elements>
1946     struct StringMaker<std::variant<Elements...>> {
convertCatch::StringMaker1947         static std::string convert(const std::variant<Elements...>& variant) {
1948             if (variant.valueless_by_exception()) {
1949                 return "{valueless variant}";
1950             } else {
1951                 return std::visit(
1952                     [](const auto& value) {
1953                         return ::Catch::Detail::stringify(value);
1954                     },
1955                     variant
1956                 );
1957             }
1958         }
1959     };
1960 }
1961 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1962 
1963 namespace Catch {
1964     struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
1965 
1966     // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
1967     using std::begin;
1968     using std::end;
1969 
1970     not_this_one begin( ... );
1971     not_this_one end( ... );
1972 
1973     template <typename T>
1974     struct is_range {
1975         static const bool value =
1976             !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
1977             !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
1978     };
1979 
1980 #if defined(_MANAGED) // Managed types are never ranges
1981     template <typename T>
1982     struct is_range<T^> {
1983         static const bool value = false;
1984     };
1985 #endif
1986 
1987     template<typename Range>
rangeToString(Range const & range)1988     std::string rangeToString( Range const& range ) {
1989         return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
1990     }
1991 
1992     // Handle vector<bool> specially
1993     template<typename Allocator>
rangeToString(std::vector<bool,Allocator> const & v)1994     std::string rangeToString( std::vector<bool, Allocator> const& v ) {
1995         ReusableStringStream rss;
1996         rss << "{ ";
1997         bool first = true;
1998         for( bool b : v ) {
1999             if( first )
2000                 first = false;
2001             else
2002                 rss << ", ";
2003             rss << ::Catch::Detail::stringify( b );
2004         }
2005         rss << " }";
2006         return rss.str();
2007     }
2008 
2009     template<typename R>
2010     struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
convertCatch::StringMaker2011         static std::string convert( R const& range ) {
2012             return rangeToString( range );
2013         }
2014     };
2015 
2016     template <typename T, int SZ>
2017     struct StringMaker<T[SZ]> {
convertCatch::StringMaker2018         static std::string convert(T const(&arr)[SZ]) {
2019             return rangeToString(arr);
2020         }
2021     };
2022 
2023 } // namespace Catch
2024 
2025 // Separate std::chrono::duration specialization
2026 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2027 #include <ctime>
2028 #include <ratio>
2029 #include <chrono>
2030 
2031 namespace Catch {
2032 
2033 template <class Ratio>
2034 struct ratio_string {
2035     static std::string symbol();
2036 };
2037 
2038 template <class Ratio>
symbol()2039 std::string ratio_string<Ratio>::symbol() {
2040     Catch::ReusableStringStream rss;
2041     rss << '[' << Ratio::num << '/'
2042         << Ratio::den << ']';
2043     return rss.str();
2044 }
2045 template <>
2046 struct ratio_string<std::atto> {
2047     static std::string symbol();
2048 };
2049 template <>
2050 struct ratio_string<std::femto> {
2051     static std::string symbol();
2052 };
2053 template <>
2054 struct ratio_string<std::pico> {
2055     static std::string symbol();
2056 };
2057 template <>
2058 struct ratio_string<std::nano> {
2059     static std::string symbol();
2060 };
2061 template <>
2062 struct ratio_string<std::micro> {
2063     static std::string symbol();
2064 };
2065 template <>
2066 struct ratio_string<std::milli> {
2067     static std::string symbol();
2068 };
2069 
2070     ////////////
2071     // std::chrono::duration specializations
2072     template<typename Value, typename Ratio>
2073     struct StringMaker<std::chrono::duration<Value, Ratio>> {
convertCatch::StringMaker2074         static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2075             ReusableStringStream rss;
2076             rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2077             return rss.str();
2078         }
2079     };
2080     template<typename Value>
2081     struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
convertCatch::StringMaker2082         static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2083             ReusableStringStream rss;
2084             rss << duration.count() << " s";
2085             return rss.str();
2086         }
2087     };
2088     template<typename Value>
2089     struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
convertCatch::StringMaker2090         static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2091             ReusableStringStream rss;
2092             rss << duration.count() << " m";
2093             return rss.str();
2094         }
2095     };
2096     template<typename Value>
2097     struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
convertCatch::StringMaker2098         static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2099             ReusableStringStream rss;
2100             rss << duration.count() << " h";
2101             return rss.str();
2102         }
2103     };
2104 
2105     ////////////
2106     // std::chrono::time_point specialization
2107     // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2108     template<typename Clock, typename Duration>
2109     struct StringMaker<std::chrono::time_point<Clock, Duration>> {
convertCatch::StringMaker2110         static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2111             return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2112         }
2113     };
2114     // std::chrono::time_point<system_clock> specialization
2115     template<typename Duration>
2116     struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
convertCatch::StringMaker2117         static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2118             auto converted = std::chrono::system_clock::to_time_t(time_point);
2119 
2120 #ifdef _MSC_VER
2121             std::tm timeInfo = {};
2122             gmtime_s(&timeInfo, &converted);
2123 #else
2124             std::tm* timeInfo = std::gmtime(&converted);
2125 #endif
2126 
2127             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2128             char timeStamp[timeStampSize];
2129             const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2130 
2131 #ifdef _MSC_VER
2132             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2133 #else
2134             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2135 #endif
2136             return std::string(timeStamp);
2137         }
2138     };
2139 }
2140 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2141 
2142 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2143 namespace Catch { \
2144     template<> struct StringMaker<enumName> { \
2145         static std::string convert( enumName value ) { \
2146             static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2147             return enumInfo.lookup( static_cast<int>( value ) ); \
2148         } \
2149     }; \
2150 }
2151 
2152 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2153 
2154 #ifdef _MSC_VER
2155 #pragma warning(pop)
2156 #endif
2157 
2158 // end catch_tostring.h
2159 #include <iosfwd>
2160 
2161 #ifdef _MSC_VER
2162 #pragma warning(push)
2163 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2164 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2165 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2166 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2167 #pragma warning(disable:4800) // Forcing result to true or false
2168 #endif
2169 
2170 namespace Catch {
2171 
2172     struct ITransientExpression {
isBinaryExpressionCatch::ITransientExpression2173         auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
getResultCatch::ITransientExpression2174         auto getResult() const -> bool { return m_result; }
2175         virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2176 
ITransientExpressionCatch::ITransientExpression2177         ITransientExpression( bool isBinaryExpression, bool result )
2178         :   m_isBinaryExpression( isBinaryExpression ),
2179             m_result( result )
2180         {}
2181 
2182         // We don't actually need a virtual destructor, but many static analysers
2183         // complain if it's not here :-(
2184         virtual ~ITransientExpression();
2185 
2186         bool m_isBinaryExpression;
2187         bool m_result;
2188 
2189     };
2190 
2191     void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2192 
2193     template<typename LhsT, typename RhsT>
2194     class BinaryExpr  : public ITransientExpression {
2195         LhsT m_lhs;
2196         StringRef m_op;
2197         RhsT m_rhs;
2198 
streamReconstructedExpression(std::ostream & os) const2199         void streamReconstructedExpression( std::ostream &os ) const override {
2200             formatReconstructedExpression
2201                     ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2202         }
2203 
2204     public:
BinaryExpr(bool comparisonResult,LhsT lhs,StringRef op,RhsT rhs)2205         BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2206         :   ITransientExpression{ true, comparisonResult },
2207             m_lhs( lhs ),
2208             m_op( op ),
2209             m_rhs( rhs )
2210         {}
2211 
2212         template<typename T>
operator &&(T) const2213         auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2214             static_assert(always_false<T>::value,
2215             "chained comparisons are not supported inside assertions, "
2216             "wrap the expression inside parentheses, or decompose it");
2217         }
2218 
2219         template<typename T>
operator ||(T) const2220         auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2221             static_assert(always_false<T>::value,
2222             "chained comparisons are not supported inside assertions, "
2223             "wrap the expression inside parentheses, or decompose it");
2224         }
2225 
2226         template<typename T>
operator ==(T) const2227         auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2228             static_assert(always_false<T>::value,
2229             "chained comparisons are not supported inside assertions, "
2230             "wrap the expression inside parentheses, or decompose it");
2231         }
2232 
2233         template<typename T>
operator !=(T) const2234         auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2235             static_assert(always_false<T>::value,
2236             "chained comparisons are not supported inside assertions, "
2237             "wrap the expression inside parentheses, or decompose it");
2238         }
2239 
2240         template<typename T>
operator >(T) const2241         auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2242             static_assert(always_false<T>::value,
2243             "chained comparisons are not supported inside assertions, "
2244             "wrap the expression inside parentheses, or decompose it");
2245         }
2246 
2247         template<typename T>
operator <(T) const2248         auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2249             static_assert(always_false<T>::value,
2250             "chained comparisons are not supported inside assertions, "
2251             "wrap the expression inside parentheses, or decompose it");
2252         }
2253 
2254         template<typename T>
operator >=(T) const2255         auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2256             static_assert(always_false<T>::value,
2257             "chained comparisons are not supported inside assertions, "
2258             "wrap the expression inside parentheses, or decompose it");
2259         }
2260 
2261         template<typename T>
operator <=(T) const2262         auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2263             static_assert(always_false<T>::value,
2264             "chained comparisons are not supported inside assertions, "
2265             "wrap the expression inside parentheses, or decompose it");
2266         }
2267     };
2268 
2269     template<typename LhsT>
2270     class UnaryExpr : public ITransientExpression {
2271         LhsT m_lhs;
2272 
streamReconstructedExpression(std::ostream & os) const2273         void streamReconstructedExpression( std::ostream &os ) const override {
2274             os << Catch::Detail::stringify( m_lhs );
2275         }
2276 
2277     public:
UnaryExpr(LhsT lhs)2278         explicit UnaryExpr( LhsT lhs )
2279         :   ITransientExpression{ false, static_cast<bool>(lhs) },
2280             m_lhs( lhs )
2281         {}
2282     };
2283 
2284     // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2285     template<typename LhsT, typename RhsT>
compareEqual(LhsT const & lhs,RhsT const & rhs)2286     auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2287     template<typename T>
compareEqual(T * const & lhs,int rhs)2288     auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2289     template<typename T>
compareEqual(T * const & lhs,long rhs)2290     auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2291     template<typename T>
compareEqual(int lhs,T * const & rhs)2292     auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2293     template<typename T>
compareEqual(long lhs,T * const & rhs)2294     auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2295 
2296     template<typename LhsT, typename RhsT>
compareNotEqual(LhsT const & lhs,RhsT && rhs)2297     auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2298     template<typename T>
compareNotEqual(T * const & lhs,int rhs)2299     auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2300     template<typename T>
compareNotEqual(T * const & lhs,long rhs)2301     auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2302     template<typename T>
compareNotEqual(int lhs,T * const & rhs)2303     auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2304     template<typename T>
compareNotEqual(long lhs,T * const & rhs)2305     auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2306 
2307     template<typename LhsT>
2308     class ExprLhs {
2309         LhsT m_lhs;
2310     public:
ExprLhs(LhsT lhs)2311         explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2312 
2313         template<typename RhsT>
operator ==(RhsT const & rhs)2314         auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2315             return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2316         }
operator ==(bool rhs)2317         auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2318             return { m_lhs == rhs, m_lhs, "==", rhs };
2319         }
2320 
2321         template<typename RhsT>
operator !=(RhsT const & rhs)2322         auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2323             return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2324         }
operator !=(bool rhs)2325         auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2326             return { m_lhs != rhs, m_lhs, "!=", rhs };
2327         }
2328 
2329         template<typename RhsT>
operator >(RhsT const & rhs)2330         auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2331             return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2332         }
2333         template<typename RhsT>
operator <(RhsT const & rhs)2334         auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2335             return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2336         }
2337         template<typename RhsT>
operator >=(RhsT const & rhs)2338         auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2339             return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2340         }
2341         template<typename RhsT>
operator <=(RhsT const & rhs)2342         auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2343             return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2344         }
2345 
2346         template<typename RhsT>
operator &&(RhsT const &)2347         auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2348             static_assert(always_false<RhsT>::value,
2349             "operator&& is not supported inside assertions, "
2350             "wrap the expression inside parentheses, or decompose it");
2351         }
2352 
2353         template<typename RhsT>
operator ||(RhsT const &)2354         auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2355             static_assert(always_false<RhsT>::value,
2356             "operator|| is not supported inside assertions, "
2357             "wrap the expression inside parentheses, or decompose it");
2358         }
2359 
makeUnaryExpr() const2360         auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2361             return UnaryExpr<LhsT>{ m_lhs };
2362         }
2363     };
2364 
2365     void handleExpression( ITransientExpression const& expr );
2366 
2367     template<typename T>
handleExpression(ExprLhs<T> const & expr)2368     void handleExpression( ExprLhs<T> const& expr ) {
2369         handleExpression( expr.makeUnaryExpr() );
2370     }
2371 
2372     struct Decomposer {
2373         template<typename T>
operator <=Catch::Decomposer2374         auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2375             return ExprLhs<T const&>{ lhs };
2376         }
2377 
operator <=Catch::Decomposer2378         auto operator <=( bool value ) -> ExprLhs<bool> {
2379             return ExprLhs<bool>{ value };
2380         }
2381     };
2382 
2383 } // end namespace Catch
2384 
2385 #ifdef _MSC_VER
2386 #pragma warning(pop)
2387 #endif
2388 
2389 // end catch_decomposer.h
2390 // start catch_interfaces_capture.h
2391 
2392 #include <string>
2393 #include <chrono>
2394 
2395 namespace Catch {
2396 
2397     class AssertionResult;
2398     struct AssertionInfo;
2399     struct SectionInfo;
2400     struct SectionEndInfo;
2401     struct MessageInfo;
2402     struct MessageBuilder;
2403     struct Counts;
2404     struct AssertionReaction;
2405     struct SourceLineInfo;
2406 
2407     struct ITransientExpression;
2408     struct IGeneratorTracker;
2409 
2410 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2411     struct BenchmarkInfo;
2412     template <typename Duration = std::chrono::duration<double, std::nano>>
2413     struct BenchmarkStats;
2414 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2415 
2416     struct IResultCapture {
2417 
2418         virtual ~IResultCapture();
2419 
2420         virtual bool sectionStarted(    SectionInfo const& sectionInfo,
2421                                         Counts& assertions ) = 0;
2422         virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2423         virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2424 
2425         virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2426 
2427 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2428         virtual void benchmarkPreparing( std::string const& name ) = 0;
2429         virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2430         virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2431         virtual void benchmarkFailed( std::string const& error ) = 0;
2432 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2433 
2434         virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2435         virtual void popScopedMessage( MessageInfo const& message ) = 0;
2436 
2437         virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2438 
2439         virtual void handleFatalErrorCondition( StringRef message ) = 0;
2440 
2441         virtual void handleExpr
2442                 (   AssertionInfo const& info,
2443                     ITransientExpression const& expr,
2444                     AssertionReaction& reaction ) = 0;
2445         virtual void handleMessage
2446                 (   AssertionInfo const& info,
2447                     ResultWas::OfType resultType,
2448                     StringRef const& message,
2449                     AssertionReaction& reaction ) = 0;
2450         virtual void handleUnexpectedExceptionNotThrown
2451                 (   AssertionInfo const& info,
2452                     AssertionReaction& reaction ) = 0;
2453         virtual void handleUnexpectedInflightException
2454                 (   AssertionInfo const& info,
2455                     std::string const& message,
2456                     AssertionReaction& reaction ) = 0;
2457         virtual void handleIncomplete
2458                 (   AssertionInfo const& info ) = 0;
2459         virtual void handleNonExpr
2460                 (   AssertionInfo const &info,
2461                     ResultWas::OfType resultType,
2462                     AssertionReaction &reaction ) = 0;
2463 
2464         virtual bool lastAssertionPassed() = 0;
2465         virtual void assertionPassed() = 0;
2466 
2467         // Deprecated, do not use:
2468         virtual std::string getCurrentTestName() const = 0;
2469         virtual const AssertionResult* getLastResult() const = 0;
2470         virtual void exceptionEarlyReported() = 0;
2471     };
2472 
2473     IResultCapture& getResultCapture();
2474 }
2475 
2476 // end catch_interfaces_capture.h
2477 namespace Catch {
2478 
2479     struct TestFailureException{};
2480     struct AssertionResultData;
2481     struct IResultCapture;
2482     class RunContext;
2483 
2484     class LazyExpression {
2485         friend class AssertionHandler;
2486         friend struct AssertionStats;
2487         friend class RunContext;
2488 
2489         ITransientExpression const* m_transientExpression = nullptr;
2490         bool m_isNegated;
2491     public:
2492         LazyExpression( bool isNegated );
2493         LazyExpression( LazyExpression const& other );
2494         LazyExpression& operator = ( LazyExpression const& ) = delete;
2495 
2496         explicit operator bool() const;
2497 
2498         friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2499     };
2500 
2501     struct AssertionReaction {
2502         bool shouldDebugBreak = false;
2503         bool shouldThrow = false;
2504     };
2505 
2506     class AssertionHandler {
2507         AssertionInfo m_assertionInfo;
2508         AssertionReaction m_reaction;
2509         bool m_completed = false;
2510         IResultCapture& m_resultCapture;
2511 
2512     public:
2513         AssertionHandler
2514             (   StringRef const& macroName,
2515                 SourceLineInfo const& lineInfo,
2516                 StringRef capturedExpression,
2517                 ResultDisposition::Flags resultDisposition );
~AssertionHandler()2518         ~AssertionHandler() {
2519             if ( !m_completed ) {
2520                 m_resultCapture.handleIncomplete( m_assertionInfo );
2521             }
2522         }
2523 
2524         template<typename T>
handleExpr(ExprLhs<T> const & expr)2525         void handleExpr( ExprLhs<T> const& expr ) {
2526             handleExpr( expr.makeUnaryExpr() );
2527         }
2528         void handleExpr( ITransientExpression const& expr );
2529 
2530         void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2531 
2532         void handleExceptionThrownAsExpected();
2533         void handleUnexpectedExceptionNotThrown();
2534         void handleExceptionNotThrownAsExpected();
2535         void handleThrowingCallSkipped();
2536         void handleUnexpectedInflightException();
2537 
2538         void complete();
2539         void setCompleted();
2540 
2541         // query
2542         auto allowThrows() const -> bool;
2543     };
2544 
2545     void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2546 
2547 } // namespace Catch
2548 
2549 // end catch_assertionhandler.h
2550 // start catch_message.h
2551 
2552 #include <string>
2553 #include <vector>
2554 
2555 namespace Catch {
2556 
2557     struct MessageInfo {
2558         MessageInfo(    StringRef const& _macroName,
2559                         SourceLineInfo const& _lineInfo,
2560                         ResultWas::OfType _type );
2561 
2562         StringRef macroName;
2563         std::string message;
2564         SourceLineInfo lineInfo;
2565         ResultWas::OfType type;
2566         unsigned int sequence;
2567 
2568         bool operator == ( MessageInfo const& other ) const;
2569         bool operator < ( MessageInfo const& other ) const;
2570     private:
2571         static unsigned int globalCount;
2572     };
2573 
2574     struct MessageStream {
2575 
2576         template<typename T>
operator <<Catch::MessageStream2577         MessageStream& operator << ( T const& value ) {
2578             m_stream << value;
2579             return *this;
2580         }
2581 
2582         ReusableStringStream m_stream;
2583     };
2584 
2585     struct MessageBuilder : MessageStream {
2586         MessageBuilder( StringRef const& macroName,
2587                         SourceLineInfo const& lineInfo,
2588                         ResultWas::OfType type );
2589 
2590         template<typename T>
operator <<Catch::MessageBuilder2591         MessageBuilder& operator << ( T const& value ) {
2592             m_stream << value;
2593             return *this;
2594         }
2595 
2596         MessageInfo m_info;
2597     };
2598 
2599     class ScopedMessage {
2600     public:
2601         explicit ScopedMessage( MessageBuilder const& builder );
2602         ScopedMessage( ScopedMessage& duplicate ) = delete;
2603         ScopedMessage( ScopedMessage&& old );
2604         ~ScopedMessage();
2605 
2606         MessageInfo m_info;
2607         bool m_moved;
2608     };
2609 
2610     class Capturer {
2611         std::vector<MessageInfo> m_messages;
2612         IResultCapture& m_resultCapture = getResultCapture();
2613         size_t m_captured = 0;
2614     public:
2615         Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2616         ~Capturer();
2617 
2618         void captureValue( size_t index, std::string const& value );
2619 
2620         template<typename T>
captureValues(size_t index,T const & value)2621         void captureValues( size_t index, T const& value ) {
2622             captureValue( index, Catch::Detail::stringify( value ) );
2623         }
2624 
2625         template<typename T, typename... Ts>
captureValues(size_t index,T const & value,Ts const &...values)2626         void captureValues( size_t index, T const& value, Ts const&... values ) {
2627             captureValue( index, Catch::Detail::stringify(value) );
2628             captureValues( index+1, values... );
2629         }
2630     };
2631 
2632 } // end namespace Catch
2633 
2634 // end catch_message.h
2635 #if !defined(CATCH_CONFIG_DISABLE)
2636 
2637 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2638   #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2639 #else
2640   #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2641 #endif
2642 
2643 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2644 
2645 ///////////////////////////////////////////////////////////////////////////////
2646 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2647 // macros.
2648 #define INTERNAL_CATCH_TRY
2649 #define INTERNAL_CATCH_CATCH( capturer )
2650 
2651 #else // CATCH_CONFIG_FAST_COMPILE
2652 
2653 #define INTERNAL_CATCH_TRY try
2654 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2655 
2656 #endif
2657 
2658 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2659 
2660 ///////////////////////////////////////////////////////////////////////////////
2661 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2662     do { \
2663         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2664         INTERNAL_CATCH_TRY { \
2665             CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2666             catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2667             CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2668         } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2669         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2670     } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
2671     // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
2672 
2673 ///////////////////////////////////////////////////////////////////////////////
2674 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2675     INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2676     if( Catch::getResultCapture().lastAssertionPassed() )
2677 
2678 ///////////////////////////////////////////////////////////////////////////////
2679 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2680     INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2681     if( !Catch::getResultCapture().lastAssertionPassed() )
2682 
2683 ///////////////////////////////////////////////////////////////////////////////
2684 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2685     do { \
2686         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2687         try { \
2688             static_cast<void>(__VA_ARGS__); \
2689             catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2690         } \
2691         catch( ... ) { \
2692             catchAssertionHandler.handleUnexpectedInflightException(); \
2693         } \
2694         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2695     } while( false )
2696 
2697 ///////////////////////////////////////////////////////////////////////////////
2698 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2699     do { \
2700         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2701         if( catchAssertionHandler.allowThrows() ) \
2702             try { \
2703                 static_cast<void>(__VA_ARGS__); \
2704                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2705             } \
2706             catch( ... ) { \
2707                 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2708             } \
2709         else \
2710             catchAssertionHandler.handleThrowingCallSkipped(); \
2711         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2712     } while( false )
2713 
2714 ///////////////////////////////////////////////////////////////////////////////
2715 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2716     do { \
2717         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2718         if( catchAssertionHandler.allowThrows() ) \
2719             try { \
2720                 static_cast<void>(expr); \
2721                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2722             } \
2723             catch( exceptionType const& ) { \
2724                 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2725             } \
2726             catch( ... ) { \
2727                 catchAssertionHandler.handleUnexpectedInflightException(); \
2728             } \
2729         else \
2730             catchAssertionHandler.handleThrowingCallSkipped(); \
2731         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2732     } while( false )
2733 
2734 ///////////////////////////////////////////////////////////////////////////////
2735 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2736     do { \
2737         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2738         catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2739         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2740     } while( false )
2741 
2742 ///////////////////////////////////////////////////////////////////////////////
2743 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2744     auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2745     varName.captureValues( 0, __VA_ARGS__ )
2746 
2747 ///////////////////////////////////////////////////////////////////////////////
2748 #define INTERNAL_CATCH_INFO( macroName, log ) \
2749     Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2750 
2751 ///////////////////////////////////////////////////////////////////////////////
2752 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2753     Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2754 
2755 ///////////////////////////////////////////////////////////////////////////////
2756 // Although this is matcher-based, it can be used with just a string
2757 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2758     do { \
2759         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2760         if( catchAssertionHandler.allowThrows() ) \
2761             try { \
2762                 static_cast<void>(__VA_ARGS__); \
2763                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2764             } \
2765             catch( ... ) { \
2766                 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2767             } \
2768         else \
2769             catchAssertionHandler.handleThrowingCallSkipped(); \
2770         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2771     } while( false )
2772 
2773 #endif // CATCH_CONFIG_DISABLE
2774 
2775 // end catch_capture.hpp
2776 // start catch_section.h
2777 
2778 // start catch_section_info.h
2779 
2780 // start catch_totals.h
2781 
2782 #include <cstddef>
2783 
2784 namespace Catch {
2785 
2786     struct Counts {
2787         Counts operator - ( Counts const& other ) const;
2788         Counts& operator += ( Counts const& other );
2789 
2790         std::size_t total() const;
2791         bool allPassed() const;
2792         bool allOk() const;
2793 
2794         std::size_t passed = 0;
2795         std::size_t failed = 0;
2796         std::size_t failedButOk = 0;
2797     };
2798 
2799     struct Totals {
2800 
2801         Totals operator - ( Totals const& other ) const;
2802         Totals& operator += ( Totals const& other );
2803 
2804         Totals delta( Totals const& prevTotals ) const;
2805 
2806         int error = 0;
2807         Counts assertions;
2808         Counts testCases;
2809     };
2810 }
2811 
2812 // end catch_totals.h
2813 #include <string>
2814 
2815 namespace Catch {
2816 
2817     struct SectionInfo {
2818         SectionInfo
2819             (   SourceLineInfo const& _lineInfo,
2820                 std::string const& _name );
2821 
2822         // Deprecated
SectionInfoCatch::SectionInfo2823         SectionInfo
2824             (   SourceLineInfo const& _lineInfo,
2825                 std::string const& _name,
2826                 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2827 
2828         std::string name;
2829         std::string description; // !Deprecated: this will always be empty
2830         SourceLineInfo lineInfo;
2831     };
2832 
2833     struct SectionEndInfo {
2834         SectionInfo sectionInfo;
2835         Counts prevAssertions;
2836         double durationInSeconds;
2837     };
2838 
2839 } // end namespace Catch
2840 
2841 // end catch_section_info.h
2842 // start catch_timer.h
2843 
2844 #include <cstdint>
2845 
2846 namespace Catch {
2847 
2848     auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2849     auto getEstimatedClockResolution() -> uint64_t;
2850 
2851     class Timer {
2852         uint64_t m_nanoseconds = 0;
2853     public:
2854         void start();
2855         auto getElapsedNanoseconds() const -> uint64_t;
2856         auto getElapsedMicroseconds() const -> uint64_t;
2857         auto getElapsedMilliseconds() const -> unsigned int;
2858         auto getElapsedSeconds() const -> double;
2859     };
2860 
2861 } // namespace Catch
2862 
2863 // end catch_timer.h
2864 #include <string>
2865 
2866 namespace Catch {
2867 
2868     class Section : NonCopyable {
2869     public:
2870         Section( SectionInfo const& info );
2871         ~Section();
2872 
2873         // This indicates whether the section should be executed or not
2874         explicit operator bool() const;
2875 
2876     private:
2877         SectionInfo m_info;
2878 
2879         std::string m_name;
2880         Counts m_assertions;
2881         bool m_sectionIncluded;
2882         Timer m_timer;
2883     };
2884 
2885 } // end namespace Catch
2886 
2887 #define INTERNAL_CATCH_SECTION( ... ) \
2888     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2889     if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2890     CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2891 
2892 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2893     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2894     if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2895     CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2896 
2897 // end catch_section.h
2898 // start catch_interfaces_exception.h
2899 
2900 // start catch_interfaces_registry_hub.h
2901 
2902 #include <string>
2903 #include <memory>
2904 
2905 namespace Catch {
2906 
2907     class TestCase;
2908     struct ITestCaseRegistry;
2909     struct IExceptionTranslatorRegistry;
2910     struct IExceptionTranslator;
2911     struct IReporterRegistry;
2912     struct IReporterFactory;
2913     struct ITagAliasRegistry;
2914     struct IMutableEnumValuesRegistry;
2915 
2916     class StartupExceptionRegistry;
2917 
2918     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2919 
2920     struct IRegistryHub {
2921         virtual ~IRegistryHub();
2922 
2923         virtual IReporterRegistry const& getReporterRegistry() const = 0;
2924         virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2925         virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2926         virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2927 
2928         virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2929     };
2930 
2931     struct IMutableRegistryHub {
2932         virtual ~IMutableRegistryHub();
2933         virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2934         virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2935         virtual void registerTest( TestCase const& testInfo ) = 0;
2936         virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2937         virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2938         virtual void registerStartupException() noexcept = 0;
2939         virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2940     };
2941 
2942     IRegistryHub const& getRegistryHub();
2943     IMutableRegistryHub& getMutableRegistryHub();
2944     void cleanUp();
2945     std::string translateActiveException();
2946 
2947 }
2948 
2949 // end catch_interfaces_registry_hub.h
2950 #if defined(CATCH_CONFIG_DISABLE)
2951     #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2952         static std::string translatorName( signature )
2953 #endif
2954 
2955 #include <exception>
2956 #include <string>
2957 #include <vector>
2958 
2959 namespace Catch {
2960     using exceptionTranslateFunction = std::string(*)();
2961 
2962     struct IExceptionTranslator;
2963     using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
2964 
2965     struct IExceptionTranslator {
2966         virtual ~IExceptionTranslator();
2967         virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
2968     };
2969 
2970     struct IExceptionTranslatorRegistry {
2971         virtual ~IExceptionTranslatorRegistry();
2972 
2973         virtual std::string translateActiveException() const = 0;
2974     };
2975 
2976     class ExceptionTranslatorRegistrar {
2977         template<typename T>
2978         class ExceptionTranslator : public IExceptionTranslator {
2979         public:
2980 
ExceptionTranslator(std::string (* translateFunction)(T &))2981             ExceptionTranslator( std::string(*translateFunction)( T& ) )
2982             : m_translateFunction( translateFunction )
2983             {}
2984 
translate(ExceptionTranslators::const_iterator it,ExceptionTranslators::const_iterator itEnd) const2985             std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
2986                 try {
2987                     if( it == itEnd )
2988                         std::rethrow_exception(std::current_exception());
2989                     else
2990                         return (*it)->translate( it+1, itEnd );
2991                 }
2992                 catch( T& ex ) {
2993                     return m_translateFunction( ex );
2994                 }
2995             }
2996 
2997         protected:
2998             std::string(*m_translateFunction)( T& );
2999         };
3000 
3001     public:
3002         template<typename T>
ExceptionTranslatorRegistrar(std::string (* translateFunction)(T &))3003         ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3004             getMutableRegistryHub().registerTranslator
3005                 ( new ExceptionTranslator<T>( translateFunction ) );
3006         }
3007     };
3008 }
3009 
3010 ///////////////////////////////////////////////////////////////////////////////
3011 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3012     static std::string translatorName( signature ); \
3013     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3014     namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3015     CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
3016     static std::string translatorName( signature )
3017 
3018 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3019 
3020 // end catch_interfaces_exception.h
3021 // start catch_approx.h
3022 
3023 #include <type_traits>
3024 
3025 namespace Catch {
3026 namespace Detail {
3027 
3028     class Approx {
3029     private:
3030         bool equalityComparisonImpl(double other) const;
3031         // Validates the new margin (margin >= 0)
3032         // out-of-line to avoid including stdexcept in the header
3033         void setMargin(double margin);
3034         // Validates the new epsilon (0 < epsilon < 1)
3035         // out-of-line to avoid including stdexcept in the header
3036         void setEpsilon(double epsilon);
3037 
3038     public:
3039         explicit Approx ( double value );
3040 
3041         static Approx custom();
3042 
3043         Approx operator-() const;
3044 
3045         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ()(T const & value)3046         Approx operator()( T const& value ) {
3047             Approx approx( static_cast<double>(value) );
3048             approx.m_epsilon = m_epsilon;
3049             approx.m_margin = m_margin;
3050             approx.m_scale = m_scale;
3051             return approx;
3052         }
3053 
3054         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx(T const & value)3055         explicit Approx( T const& value ): Approx(static_cast<double>(value))
3056         {}
3057 
3058         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(const T & lhs,Approx const & rhs)3059         friend bool operator == ( const T& lhs, Approx const& rhs ) {
3060             auto lhs_v = static_cast<double>(lhs);
3061             return rhs.equalityComparisonImpl(lhs_v);
3062         }
3063 
3064         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(Approx const & lhs,const T & rhs)3065         friend bool operator == ( Approx const& lhs, const T& rhs ) {
3066             return operator==( rhs, lhs );
3067         }
3068 
3069         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(T const & lhs,Approx const & rhs)3070         friend bool operator != ( T const& lhs, Approx const& rhs ) {
3071             return !operator==( lhs, rhs );
3072         }
3073 
3074         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(Approx const & lhs,T const & rhs)3075         friend bool operator != ( Approx const& lhs, T const& rhs ) {
3076             return !operator==( rhs, lhs );
3077         }
3078 
3079         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(T const & lhs,Approx const & rhs)3080         friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3081             return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3082         }
3083 
3084         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(Approx const & lhs,T const & rhs)3085         friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3086             return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3087         }
3088 
3089         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(T const & lhs,Approx const & rhs)3090         friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3091             return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3092         }
3093 
3094         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(Approx const & lhs,T const & rhs)3095         friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3096             return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3097         }
3098 
3099         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilon(T const & newEpsilon)3100         Approx& epsilon( T const& newEpsilon ) {
3101             double epsilonAsDouble = static_cast<double>(newEpsilon);
3102             setEpsilon(epsilonAsDouble);
3103             return *this;
3104         }
3105 
3106         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
margin(T const & newMargin)3107         Approx& margin( T const& newMargin ) {
3108             double marginAsDouble = static_cast<double>(newMargin);
3109             setMargin(marginAsDouble);
3110             return *this;
3111         }
3112 
3113         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scale(T const & newScale)3114         Approx& scale( T const& newScale ) {
3115             m_scale = static_cast<double>(newScale);
3116             return *this;
3117         }
3118 
3119         std::string toString() const;
3120 
3121     private:
3122         double m_epsilon;
3123         double m_margin;
3124         double m_scale;
3125         double m_value;
3126     };
3127 } // end namespace Detail
3128 
3129 namespace literals {
3130     Detail::Approx operator "" _a(long double val);
3131     Detail::Approx operator "" _a(unsigned long long val);
3132 } // end namespace literals
3133 
3134 template<>
3135 struct StringMaker<Catch::Detail::Approx> {
3136     static std::string convert(Catch::Detail::Approx const& value);
3137 };
3138 
3139 } // end namespace Catch
3140 
3141 // end catch_approx.h
3142 // start catch_string_manip.h
3143 
3144 #include <string>
3145 #include <iosfwd>
3146 #include <vector>
3147 
3148 namespace Catch {
3149 
3150     bool startsWith( std::string const& s, std::string const& prefix );
3151     bool startsWith( std::string const& s, char prefix );
3152     bool endsWith( std::string const& s, std::string const& suffix );
3153     bool endsWith( std::string const& s, char suffix );
3154     bool contains( std::string const& s, std::string const& infix );
3155     void toLowerInPlace( std::string& s );
3156     std::string toLower( std::string const& s );
3157     std::string trim( std::string const& str );
3158 
3159     // !!! Be aware, returns refs into original string - make sure original string outlives them
3160     std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3161     bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3162 
3163     struct pluralise {
3164         pluralise( std::size_t count, std::string const& label );
3165 
3166         friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3167 
3168         std::size_t m_count;
3169         std::string m_label;
3170     };
3171 }
3172 
3173 // end catch_string_manip.h
3174 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3175 // start catch_capture_matchers.h
3176 
3177 // start catch_matchers.h
3178 
3179 #include <string>
3180 #include <vector>
3181 
3182 namespace Catch {
3183 namespace Matchers {
3184     namespace Impl {
3185 
3186         template<typename ArgT> struct MatchAllOf;
3187         template<typename ArgT> struct MatchAnyOf;
3188         template<typename ArgT> struct MatchNotOf;
3189 
3190         class MatcherUntypedBase {
3191         public:
3192             MatcherUntypedBase() = default;
3193             MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3194             MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3195             std::string toString() const;
3196 
3197         protected:
3198             virtual ~MatcherUntypedBase();
3199             virtual std::string describe() const = 0;
3200             mutable std::string m_cachedToString;
3201         };
3202 
3203 #ifdef __clang__
3204 #    pragma clang diagnostic push
3205 #    pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3206 #endif
3207 
3208         template<typename ObjectT>
3209         struct MatcherMethod {
3210             virtual bool match( ObjectT const& arg ) const = 0;
3211         };
3212 
3213 #if defined(__OBJC__)
3214         // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3215         // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3216         template<>
3217         struct MatcherMethod<NSString*> {
3218             virtual bool match( NSString* arg ) const = 0;
3219         };
3220 #endif
3221 
3222 #ifdef __clang__
3223 #    pragma clang diagnostic pop
3224 #endif
3225 
3226         template<typename T>
3227         struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3228 
3229             MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3230             MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3231             MatchNotOf<T> operator ! () const;
3232         };
3233 
3234         template<typename ArgT>
3235         struct MatchAllOf : MatcherBase<ArgT> {
matchCatch::Matchers::Impl::MatchAllOf3236             bool match( ArgT const& arg ) const override {
3237                 for( auto matcher : m_matchers ) {
3238                     if (!matcher->match(arg))
3239                         return false;
3240                 }
3241                 return true;
3242             }
describeCatch::Matchers::Impl::MatchAllOf3243             std::string describe() const override {
3244                 std::string description;
3245                 description.reserve( 4 + m_matchers.size()*32 );
3246                 description += "( ";
3247                 bool first = true;
3248                 for( auto matcher : m_matchers ) {
3249                     if( first )
3250                         first = false;
3251                     else
3252                         description += " and ";
3253                     description += matcher->toString();
3254                 }
3255                 description += " )";
3256                 return description;
3257             }
3258 
operator &&Catch::Matchers::Impl::MatchAllOf3259             MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
3260                 m_matchers.push_back( &other );
3261                 return *this;
3262             }
3263 
3264             std::vector<MatcherBase<ArgT> const*> m_matchers;
3265         };
3266         template<typename ArgT>
3267         struct MatchAnyOf : MatcherBase<ArgT> {
3268 
matchCatch::Matchers::Impl::MatchAnyOf3269             bool match( ArgT const& arg ) const override {
3270                 for( auto matcher : m_matchers ) {
3271                     if (matcher->match(arg))
3272                         return true;
3273                 }
3274                 return false;
3275             }
describeCatch::Matchers::Impl::MatchAnyOf3276             std::string describe() const override {
3277                 std::string description;
3278                 description.reserve( 4 + m_matchers.size()*32 );
3279                 description += "( ";
3280                 bool first = true;
3281                 for( auto matcher : m_matchers ) {
3282                     if( first )
3283                         first = false;
3284                     else
3285                         description += " or ";
3286                     description += matcher->toString();
3287                 }
3288                 description += " )";
3289                 return description;
3290             }
3291 
operator ||Catch::Matchers::Impl::MatchAnyOf3292             MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
3293                 m_matchers.push_back( &other );
3294                 return *this;
3295             }
3296 
3297             std::vector<MatcherBase<ArgT> const*> m_matchers;
3298         };
3299 
3300         template<typename ArgT>
3301         struct MatchNotOf : MatcherBase<ArgT> {
3302 
MatchNotOfCatch::Matchers::Impl::MatchNotOf3303             MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3304 
matchCatch::Matchers::Impl::MatchNotOf3305             bool match( ArgT const& arg ) const override {
3306                 return !m_underlyingMatcher.match( arg );
3307             }
3308 
describeCatch::Matchers::Impl::MatchNotOf3309             std::string describe() const override {
3310                 return "not " + m_underlyingMatcher.toString();
3311             }
3312             MatcherBase<ArgT> const& m_underlyingMatcher;
3313         };
3314 
3315         template<typename T>
operator &&(MatcherBase const & other) const3316         MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
3317             return MatchAllOf<T>() && *this && other;
3318         }
3319         template<typename T>
operator ||(MatcherBase const & other) const3320         MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3321             return MatchAnyOf<T>() || *this || other;
3322         }
3323         template<typename T>
operator !() const3324         MatchNotOf<T> MatcherBase<T>::operator ! () const {
3325             return MatchNotOf<T>( *this );
3326         }
3327 
3328     } // namespace Impl
3329 
3330 } // namespace Matchers
3331 
3332 using namespace Matchers;
3333 using Matchers::Impl::MatcherBase;
3334 
3335 } // namespace Catch
3336 
3337 // end catch_matchers.h
3338 // start catch_matchers_floating.h
3339 
3340 #include <type_traits>
3341 #include <cmath>
3342 
3343 namespace Catch {
3344 namespace Matchers {
3345 
3346     namespace Floating {
3347 
3348         enum class FloatingPointKind : uint8_t;
3349 
3350         struct WithinAbsMatcher : MatcherBase<double> {
3351             WithinAbsMatcher(double target, double margin);
3352             bool match(double const& matchee) const override;
3353             std::string describe() const override;
3354         private:
3355             double m_target;
3356             double m_margin;
3357         };
3358 
3359         struct WithinUlpsMatcher : MatcherBase<double> {
3360             WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
3361             bool match(double const& matchee) const override;
3362             std::string describe() const override;
3363         private:
3364             double m_target;
3365             int m_ulps;
3366             FloatingPointKind m_type;
3367         };
3368 
3369     } // namespace Floating
3370 
3371     // The following functions create the actual matcher objects.
3372     // This allows the types to be inferred
3373     Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
3374     Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
3375     Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3376 
3377 } // namespace Matchers
3378 } // namespace Catch
3379 
3380 // end catch_matchers_floating.h
3381 // start catch_matchers_generic.hpp
3382 
3383 #include <functional>
3384 #include <string>
3385 
3386 namespace Catch {
3387 namespace Matchers {
3388 namespace Generic {
3389 
3390 namespace Detail {
3391     std::string finalizeDescription(const std::string& desc);
3392 }
3393 
3394 template <typename T>
3395 class PredicateMatcher : public MatcherBase<T> {
3396     std::function<bool(T const&)> m_predicate;
3397     std::string m_description;
3398 public:
3399 
PredicateMatcher(std::function<bool (T const &)> const & elem,std::string const & descr)3400     PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3401         :m_predicate(std::move(elem)),
3402         m_description(Detail::finalizeDescription(descr))
3403     {}
3404 
match(T const & item) const3405     bool match( T const& item ) const override {
3406         return m_predicate(item);
3407     }
3408 
describe() const3409     std::string describe() const override {
3410         return m_description;
3411     }
3412 };
3413 
3414 } // namespace Generic
3415 
3416     // The following functions create the actual matcher objects.
3417     // The user has to explicitly specify type to the function, because
3418     // inferring std::function<bool(T const&)> is hard (but possible) and
3419     // requires a lot of TMP.
3420     template<typename T>
Predicate(std::function<bool (T const &)> const & predicate,std::string const & description="")3421     Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3422         return Generic::PredicateMatcher<T>(predicate, description);
3423     }
3424 
3425 } // namespace Matchers
3426 } // namespace Catch
3427 
3428 // end catch_matchers_generic.hpp
3429 // start catch_matchers_string.h
3430 
3431 #include <string>
3432 
3433 namespace Catch {
3434 namespace Matchers {
3435 
3436     namespace StdString {
3437 
3438         struct CasedString
3439         {
3440             CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3441             std::string adjustString( std::string const& str ) const;
3442             std::string caseSensitivitySuffix() const;
3443 
3444             CaseSensitive::Choice m_caseSensitivity;
3445             std::string m_str;
3446         };
3447 
3448         struct StringMatcherBase : MatcherBase<std::string> {
3449             StringMatcherBase( std::string const& operation, CasedString const& comparator );
3450             std::string describe() const override;
3451 
3452             CasedString m_comparator;
3453             std::string m_operation;
3454         };
3455 
3456         struct EqualsMatcher : StringMatcherBase {
3457             EqualsMatcher( CasedString const& comparator );
3458             bool match( std::string const& source ) const override;
3459         };
3460         struct ContainsMatcher : StringMatcherBase {
3461             ContainsMatcher( CasedString const& comparator );
3462             bool match( std::string const& source ) const override;
3463         };
3464         struct StartsWithMatcher : StringMatcherBase {
3465             StartsWithMatcher( CasedString const& comparator );
3466             bool match( std::string const& source ) const override;
3467         };
3468         struct EndsWithMatcher : StringMatcherBase {
3469             EndsWithMatcher( CasedString const& comparator );
3470             bool match( std::string const& source ) const override;
3471         };
3472 
3473         struct RegexMatcher : MatcherBase<std::string> {
3474             RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3475             bool match( std::string const& matchee ) const override;
3476             std::string describe() const override;
3477 
3478         private:
3479             std::string m_regex;
3480             CaseSensitive::Choice m_caseSensitivity;
3481         };
3482 
3483     } // namespace StdString
3484 
3485     // The following functions create the actual matcher objects.
3486     // This allows the types to be inferred
3487 
3488     StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3489     StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3490     StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3491     StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3492     StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3493 
3494 } // namespace Matchers
3495 } // namespace Catch
3496 
3497 // end catch_matchers_string.h
3498 // start catch_matchers_vector.h
3499 
3500 #include <algorithm>
3501 
3502 namespace Catch {
3503 namespace Matchers {
3504 
3505     namespace Vector {
3506         template<typename T>
3507         struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
3508 
ContainsElementMatcherCatch::Matchers::Vector::ContainsElementMatcher3509             ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3510 
matchCatch::Matchers::Vector::ContainsElementMatcher3511             bool match(std::vector<T> const &v) const override {
3512                 for (auto const& el : v) {
3513                     if (el == m_comparator) {
3514                         return true;
3515                     }
3516                 }
3517                 return false;
3518             }
3519 
describeCatch::Matchers::Vector::ContainsElementMatcher3520             std::string describe() const override {
3521                 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3522             }
3523 
3524             T const& m_comparator;
3525         };
3526 
3527         template<typename T>
3528         struct ContainsMatcher : MatcherBase<std::vector<T>> {
3529 
ContainsMatcherCatch::Matchers::Vector::ContainsMatcher3530             ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3531 
matchCatch::Matchers::Vector::ContainsMatcher3532             bool match(std::vector<T> const &v) const override {
3533                 // !TBD: see note in EqualsMatcher
3534                 if (m_comparator.size() > v.size())
3535                     return false;
3536                 for (auto const& comparator : m_comparator) {
3537                     auto present = false;
3538                     for (const auto& el : v) {
3539                         if (el == comparator) {
3540                             present = true;
3541                             break;
3542                         }
3543                     }
3544                     if (!present) {
3545                         return false;
3546                     }
3547                 }
3548                 return true;
3549             }
describeCatch::Matchers::Vector::ContainsMatcher3550             std::string describe() const override {
3551                 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3552             }
3553 
3554             std::vector<T> const& m_comparator;
3555         };
3556 
3557         template<typename T>
3558         struct EqualsMatcher : MatcherBase<std::vector<T>> {
3559 
EqualsMatcherCatch::Matchers::Vector::EqualsMatcher3560             EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3561 
matchCatch::Matchers::Vector::EqualsMatcher3562             bool match(std::vector<T> const &v) const override {
3563                 // !TBD: This currently works if all elements can be compared using !=
3564                 // - a more general approach would be via a compare template that defaults
3565                 // to using !=. but could be specialised for, e.g. std::vector<T> etc
3566                 // - then just call that directly
3567                 if (m_comparator.size() != v.size())
3568                     return false;
3569                 for (std::size_t i = 0; i < v.size(); ++i)
3570                     if (m_comparator[i] != v[i])
3571                         return false;
3572                 return true;
3573             }
describeCatch::Matchers::Vector::EqualsMatcher3574             std::string describe() const override {
3575                 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3576             }
3577             std::vector<T> const& m_comparator;
3578         };
3579 
3580         template<typename T>
3581         struct ApproxMatcher : MatcherBase<std::vector<T>> {
3582 
ApproxMatcherCatch::Matchers::Vector::ApproxMatcher3583             ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
3584 
matchCatch::Matchers::Vector::ApproxMatcher3585             bool match(std::vector<T> const &v) const override {
3586                 if (m_comparator.size() != v.size())
3587                     return false;
3588                 for (std::size_t i = 0; i < v.size(); ++i)
3589                     if (m_comparator[i] != approx(v[i]))
3590                         return false;
3591                 return true;
3592             }
describeCatch::Matchers::Vector::ApproxMatcher3593             std::string describe() const override {
3594                 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3595             }
3596             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilonCatch::Matchers::Vector::ApproxMatcher3597             ApproxMatcher& epsilon( T const& newEpsilon ) {
3598                 approx.epsilon(newEpsilon);
3599                 return *this;
3600             }
3601             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
marginCatch::Matchers::Vector::ApproxMatcher3602             ApproxMatcher& margin( T const& newMargin ) {
3603                 approx.margin(newMargin);
3604                 return *this;
3605             }
3606             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scaleCatch::Matchers::Vector::ApproxMatcher3607             ApproxMatcher& scale( T const& newScale ) {
3608                 approx.scale(newScale);
3609                 return *this;
3610             }
3611 
3612             std::vector<T> const& m_comparator;
3613             mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3614         };
3615 
3616         template<typename T>
3617         struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
UnorderedEqualsMatcherCatch::Matchers::Vector::UnorderedEqualsMatcher3618             UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
matchCatch::Matchers::Vector::UnorderedEqualsMatcher3619             bool match(std::vector<T> const& vec) const override {
3620                 // Note: This is a reimplementation of std::is_permutation,
3621                 //       because I don't want to include <algorithm> inside the common path
3622                 if (m_target.size() != vec.size()) {
3623                     return false;
3624                 }
3625                 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3626             }
3627 
describeCatch::Matchers::Vector::UnorderedEqualsMatcher3628             std::string describe() const override {
3629                 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3630             }
3631         private:
3632             std::vector<T> const& m_target;
3633         };
3634 
3635     } // namespace Vector
3636 
3637     // The following functions create the actual matcher objects.
3638     // This allows the types to be inferred
3639 
3640     template<typename T>
Contains(std::vector<T> const & comparator)3641     Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
3642         return Vector::ContainsMatcher<T>( comparator );
3643     }
3644 
3645     template<typename T>
VectorContains(T const & comparator)3646     Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
3647         return Vector::ContainsElementMatcher<T>( comparator );
3648     }
3649 
3650     template<typename T>
Equals(std::vector<T> const & comparator)3651     Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
3652         return Vector::EqualsMatcher<T>( comparator );
3653     }
3654 
3655     template<typename T>
Approx(std::vector<T> const & comparator)3656     Vector::ApproxMatcher<T> Approx( std::vector<T> const& comparator ) {
3657         return Vector::ApproxMatcher<T>( comparator );
3658     }
3659 
3660     template<typename T>
UnorderedEquals(std::vector<T> const & target)3661     Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
3662         return Vector::UnorderedEqualsMatcher<T>(target);
3663     }
3664 
3665 } // namespace Matchers
3666 } // namespace Catch
3667 
3668 // end catch_matchers_vector.h
3669 namespace Catch {
3670 
3671     template<typename ArgT, typename MatcherT>
3672     class MatchExpr : public ITransientExpression {
3673         ArgT const& m_arg;
3674         MatcherT m_matcher;
3675         StringRef m_matcherString;
3676     public:
MatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3677         MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3678         :   ITransientExpression{ true, matcher.match( arg ) },
3679             m_arg( arg ),
3680             m_matcher( matcher ),
3681             m_matcherString( matcherString )
3682         {}
3683 
streamReconstructedExpression(std::ostream & os) const3684         void streamReconstructedExpression( std::ostream &os ) const override {
3685             auto matcherAsString = m_matcher.toString();
3686             os << Catch::Detail::stringify( m_arg ) << ' ';
3687             if( matcherAsString == Detail::unprintableString )
3688                 os << m_matcherString;
3689             else
3690                 os << matcherAsString;
3691         }
3692     };
3693 
3694     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
3695 
3696     void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  );
3697 
3698     template<typename ArgT, typename MatcherT>
makeMatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3699     auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString  ) -> MatchExpr<ArgT, MatcherT> {
3700         return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3701     }
3702 
3703 } // namespace Catch
3704 
3705 ///////////////////////////////////////////////////////////////////////////////
3706 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3707     do { \
3708         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3709         INTERNAL_CATCH_TRY { \
3710             catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3711         } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3712         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3713     } while( false )
3714 
3715 ///////////////////////////////////////////////////////////////////////////////
3716 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3717     do { \
3718         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3719         if( catchAssertionHandler.allowThrows() ) \
3720             try { \
3721                 static_cast<void>(__VA_ARGS__ ); \
3722                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3723             } \
3724             catch( exceptionType const& ex ) { \
3725                 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3726             } \
3727             catch( ... ) { \
3728                 catchAssertionHandler.handleUnexpectedInflightException(); \
3729             } \
3730         else \
3731             catchAssertionHandler.handleThrowingCallSkipped(); \
3732         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3733     } while( false )
3734 
3735 // end catch_capture_matchers.h
3736 #endif
3737 // start catch_generators.hpp
3738 
3739 // start catch_interfaces_generatortracker.h
3740 
3741 
3742 #include <memory>
3743 
3744 namespace Catch {
3745 
3746     namespace Generators {
3747         class GeneratorUntypedBase {
3748         public:
3749             GeneratorUntypedBase() = default;
3750             virtual ~GeneratorUntypedBase();
3751             // Attempts to move the generator to the next element
3752              //
3753              // Returns true iff the move succeeded (and a valid element
3754              // can be retrieved).
3755             virtual bool next() = 0;
3756         };
3757         using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3758 
3759     } // namespace Generators
3760 
3761     struct IGeneratorTracker {
3762         virtual ~IGeneratorTracker();
3763         virtual auto hasGenerator() const -> bool = 0;
3764         virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3765         virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3766     };
3767 
3768 } // namespace Catch
3769 
3770 // end catch_interfaces_generatortracker.h
3771 // start catch_enforce.h
3772 
3773 #include <exception>
3774 
3775 namespace Catch {
3776 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3777     template <typename Ex>
3778     [[noreturn]]
throw_exception(Ex const & e)3779     void throw_exception(Ex const& e) {
3780         throw e;
3781     }
3782 #else // ^^ Exceptions are enabled //  Exceptions are disabled vv
3783     [[noreturn]]
3784     void throw_exception(std::exception const& e);
3785 #endif
3786 
3787     [[noreturn]]
3788     void throw_logic_error(std::string const& msg);
3789     [[noreturn]]
3790     void throw_domain_error(std::string const& msg);
3791     [[noreturn]]
3792     void throw_runtime_error(std::string const& msg);
3793 
3794 } // namespace Catch;
3795 
3796 #define CATCH_MAKE_MSG(...) \
3797     (Catch::ReusableStringStream() << __VA_ARGS__).str()
3798 
3799 #define CATCH_INTERNAL_ERROR(...) \
3800     Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__));
3801 
3802 #define CATCH_ERROR(...) \
3803     Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
3804 
3805 #define CATCH_RUNTIME_ERROR(...) \
3806     Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ));
3807 
3808 #define CATCH_ENFORCE( condition, ... ) \
3809     do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3810 
3811 // end catch_enforce.h
3812 #include <memory>
3813 #include <vector>
3814 #include <cassert>
3815 
3816 #include <utility>
3817 #include <exception>
3818 
3819 namespace Catch {
3820 
3821 class GeneratorException : public std::exception {
3822     const char* const m_msg = "";
3823 
3824 public:
GeneratorException(const char * msg)3825     GeneratorException(const char* msg):
3826         m_msg(msg)
3827     {}
3828 
3829     const char* what() const noexcept override final;
3830 };
3831 
3832 namespace Generators {
3833 
3834     // !TBD move this into its own location?
3835     namespace pf{
3836         template<typename T, typename... Args>
make_unique(Args &&...args)3837         std::unique_ptr<T> make_unique( Args&&... args ) {
3838             return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3839         }
3840     }
3841 
3842     template<typename T>
3843     struct IGenerator : GeneratorUntypedBase {
3844         virtual ~IGenerator() = default;
3845 
3846         // Returns the current element of the generator
3847         //
3848         // \Precondition The generator is either freshly constructed,
3849         // or the last call to `next()` returned true
3850         virtual T const& get() const = 0;
3851         using type = T;
3852     };
3853 
3854     template<typename T>
3855     class SingleValueGenerator final : public IGenerator<T> {
3856         T m_value;
3857     public:
SingleValueGenerator(T const & value)3858         SingleValueGenerator(T const& value) : m_value( value ) {}
SingleValueGenerator(T && value)3859         SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3860 
get() const3861         T const& get() const override {
3862             return m_value;
3863         }
next()3864         bool next() override {
3865             return false;
3866         }
3867     };
3868 
3869     template<typename T>
3870     class FixedValuesGenerator final : public IGenerator<T> {
3871         static_assert(!std::is_same<T, bool>::value,
3872             "ValuesGenerator does not support bools because of std::vector<bool>"
3873             "specialization, use SingleValue Generator instead.");
3874         std::vector<T> m_values;
3875         size_t m_idx = 0;
3876     public:
FixedValuesGenerator(std::initializer_list<T> values)3877         FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3878 
get() const3879         T const& get() const override {
3880             return m_values[m_idx];
3881         }
next()3882         bool next() override {
3883             ++m_idx;
3884             return m_idx < m_values.size();
3885         }
3886     };
3887 
3888     template <typename T>
3889     class GeneratorWrapper final {
3890         std::unique_ptr<IGenerator<T>> m_generator;
3891     public:
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator)3892         GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3893             m_generator(std::move(generator))
3894         {}
get() const3895         T const& get() const {
3896             return m_generator->get();
3897         }
next()3898         bool next() {
3899             return m_generator->next();
3900         }
3901     };
3902 
3903     template <typename T>
value(T && value)3904     GeneratorWrapper<T> value(T&& value) {
3905         return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
3906     }
3907     template <typename T>
values(std::initializer_list<T> values)3908     GeneratorWrapper<T> values(std::initializer_list<T> values) {
3909         return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
3910     }
3911 
3912     template<typename T>
3913     class Generators : public IGenerator<T> {
3914         std::vector<GeneratorWrapper<T>> m_generators;
3915         size_t m_current = 0;
3916 
populate(GeneratorWrapper<T> && generator)3917         void populate(GeneratorWrapper<T>&& generator) {
3918             m_generators.emplace_back(std::move(generator));
3919         }
populate(T && val)3920         void populate(T&& val) {
3921             m_generators.emplace_back(value(std::move(val)));
3922         }
3923         template<typename U>
populate(U && val)3924         void populate(U&& val) {
3925             populate(T(std::move(val)));
3926         }
3927         template<typename U, typename... Gs>
populate(U && valueOrGenerator,Gs...moreGenerators)3928         void populate(U&& valueOrGenerator, Gs... moreGenerators) {
3929             populate(std::forward<U>(valueOrGenerator));
3930             populate(std::forward<Gs>(moreGenerators)...);
3931         }
3932 
3933     public:
3934         template <typename... Gs>
Generators(Gs...moreGenerators)3935         Generators(Gs... moreGenerators) {
3936             m_generators.reserve(sizeof...(Gs));
3937             populate(std::forward<Gs>(moreGenerators)...);
3938         }
3939 
get() const3940         T const& get() const override {
3941             return m_generators[m_current].get();
3942         }
3943 
next()3944         bool next() override {
3945             if (m_current >= m_generators.size()) {
3946                 return false;
3947             }
3948             const bool current_status = m_generators[m_current].next();
3949             if (!current_status) {
3950                 ++m_current;
3951             }
3952             return m_current < m_generators.size();
3953         }
3954     };
3955 
3956     template<typename... Ts>
table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)3957     GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
3958         return values<std::tuple<Ts...>>( tuples );
3959     }
3960 
3961     // Tag type to signal that a generator sequence should convert arguments to a specific type
3962     template <typename T>
3963     struct as {};
3964 
3965     template<typename T, typename... Gs>
makeGenerators(GeneratorWrapper<T> && generator,Gs...moreGenerators)3966     auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
3967         return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
3968     }
3969     template<typename T>
makeGenerators(GeneratorWrapper<T> && generator)3970     auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
3971         return Generators<T>(std::move(generator));
3972     }
3973     template<typename T, typename... Gs>
makeGenerators(T && val,Gs...moreGenerators)3974     auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
3975         return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
3976     }
3977     template<typename T, typename U, typename... Gs>
makeGenerators(as<T>,U && val,Gs...moreGenerators)3978     auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
3979         return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
3980     }
3981 
3982     auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
3983 
3984     template<typename L>
3985     // Note: The type after -> is weird, because VS2015 cannot parse
3986     //       the expression used in the typedef inside, when it is in
3987     //       return type. Yeah.
generate(SourceLineInfo const & lineInfo,L const & generatorExpression)3988     auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
3989         using UnderlyingType = typename decltype(generatorExpression())::type;
3990 
3991         IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
3992         if (!tracker.hasGenerator()) {
3993             tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
3994         }
3995 
3996         auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
3997         return generator.get();
3998     }
3999 
4000 } // namespace Generators
4001 } // namespace Catch
4002 
4003 #define GENERATE( ... ) \
4004     Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4005 #define GENERATE_COPY( ... ) \
4006     Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4007 #define GENERATE_REF( ... ) \
4008     Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
4009 
4010 // end catch_generators.hpp
4011 // start catch_generators_generic.hpp
4012 
4013 namespace Catch {
4014 namespace Generators {
4015 
4016     template <typename T>
4017     class TakeGenerator : public IGenerator<T> {
4018         GeneratorWrapper<T> m_generator;
4019         size_t m_returned = 0;
4020         size_t m_target;
4021     public:
TakeGenerator(size_t target,GeneratorWrapper<T> && generator)4022         TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4023             m_generator(std::move(generator)),
4024             m_target(target)
4025         {
4026             assert(target != 0 && "Empty generators are not allowed");
4027         }
get() const4028         T const& get() const override {
4029             return m_generator.get();
4030         }
next()4031         bool next() override {
4032             ++m_returned;
4033             if (m_returned >= m_target) {
4034                 return false;
4035             }
4036 
4037             const auto success = m_generator.next();
4038             // If the underlying generator does not contain enough values
4039             // then we cut short as well
4040             if (!success) {
4041                 m_returned = m_target;
4042             }
4043             return success;
4044         }
4045     };
4046 
4047     template <typename T>
take(size_t target,GeneratorWrapper<T> && generator)4048     GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4049         return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4050     }
4051 
4052     template <typename T, typename Predicate>
4053     class FilterGenerator : public IGenerator<T> {
4054         GeneratorWrapper<T> m_generator;
4055         Predicate m_predicate;
4056     public:
4057         template <typename P = Predicate>
FilterGenerator(P && pred,GeneratorWrapper<T> && generator)4058         FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4059             m_generator(std::move(generator)),
4060             m_predicate(std::forward<P>(pred))
4061         {
4062             if (!m_predicate(m_generator.get())) {
4063                 // It might happen that there are no values that pass the
4064                 // filter. In that case we throw an exception.
4065                 auto has_initial_value = next();
4066                 if (!has_initial_value) {
4067                     Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4068                 }
4069             }
4070         }
4071 
get() const4072         T const& get() const override {
4073             return m_generator.get();
4074         }
4075 
next()4076         bool next() override {
4077             bool success = m_generator.next();
4078             if (!success) {
4079                 return false;
4080             }
4081             while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4082             return success;
4083         }
4084     };
4085 
4086     template <typename T, typename Predicate>
filter(Predicate && pred,GeneratorWrapper<T> && generator)4087     GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4088         return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4089     }
4090 
4091     template <typename T>
4092     class RepeatGenerator : public IGenerator<T> {
4093         static_assert(!std::is_same<T, bool>::value,
4094             "RepeatGenerator currently does not support bools"
4095             "because of std::vector<bool> specialization");
4096         GeneratorWrapper<T> m_generator;
4097         mutable std::vector<T> m_returned;
4098         size_t m_target_repeats;
4099         size_t m_current_repeat = 0;
4100         size_t m_repeat_index = 0;
4101     public:
RepeatGenerator(size_t repeats,GeneratorWrapper<T> && generator)4102         RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4103             m_generator(std::move(generator)),
4104             m_target_repeats(repeats)
4105         {
4106             assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4107         }
4108 
get() const4109         T const& get() const override {
4110             if (m_current_repeat == 0) {
4111                 m_returned.push_back(m_generator.get());
4112                 return m_returned.back();
4113             }
4114             return m_returned[m_repeat_index];
4115         }
4116 
next()4117         bool next() override {
4118             // There are 2 basic cases:
4119             // 1) We are still reading the generator
4120             // 2) We are reading our own cache
4121 
4122             // In the first case, we need to poke the underlying generator.
4123             // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4124             if (m_current_repeat == 0) {
4125                 const auto success = m_generator.next();
4126                 if (!success) {
4127                     ++m_current_repeat;
4128                 }
4129                 return m_current_repeat < m_target_repeats;
4130             }
4131 
4132             // In the second case, we need to move indices forward and check that we haven't run up against the end
4133             ++m_repeat_index;
4134             if (m_repeat_index == m_returned.size()) {
4135                 m_repeat_index = 0;
4136                 ++m_current_repeat;
4137             }
4138             return m_current_repeat < m_target_repeats;
4139         }
4140     };
4141 
4142     template <typename T>
repeat(size_t repeats,GeneratorWrapper<T> && generator)4143     GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4144         return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4145     }
4146 
4147     template <typename T, typename U, typename Func>
4148     class MapGenerator : public IGenerator<T> {
4149         // TBD: provide static assert for mapping function, for friendly error message
4150         GeneratorWrapper<U> m_generator;
4151         Func m_function;
4152         // To avoid returning dangling reference, we have to save the values
4153         T m_cache;
4154     public:
4155         template <typename F2 = Func>
MapGenerator(F2 && function,GeneratorWrapper<U> && generator)4156         MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4157             m_generator(std::move(generator)),
4158             m_function(std::forward<F2>(function)),
4159             m_cache(m_function(m_generator.get()))
4160         {}
4161 
get() const4162         T const& get() const override {
4163             return m_cache;
4164         }
next()4165         bool next() override {
4166             const auto success = m_generator.next();
4167             if (success) {
4168                 m_cache = m_function(m_generator.get());
4169             }
4170             return success;
4171         }
4172     };
4173 
4174 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
4175     // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
4176     // replaced with std::invoke_result here. Also *_t format is preferred over
4177     // typename *::type format.
4178     template <typename Func, typename U>
4179     using MapFunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U>>>;
4180 #else
4181     template <typename Func, typename U>
4182     using MapFunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U)>::type>::type>::type;
4183 #endif
4184 
4185     template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
map(Func && function,GeneratorWrapper<U> && generator)4186     GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4187         return GeneratorWrapper<T>(
4188             pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4189         );
4190     }
4191 
4192     template <typename T, typename U, typename Func>
map(Func && function,GeneratorWrapper<U> && generator)4193     GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4194         return GeneratorWrapper<T>(
4195             pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4196         );
4197     }
4198 
4199     template <typename T>
4200     class ChunkGenerator final : public IGenerator<std::vector<T>> {
4201         std::vector<T> m_chunk;
4202         size_t m_chunk_size;
4203         GeneratorWrapper<T> m_generator;
4204         bool m_used_up = false;
4205     public:
ChunkGenerator(size_t size,GeneratorWrapper<T> generator)4206         ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4207             m_chunk_size(size), m_generator(std::move(generator))
4208         {
4209             m_chunk.reserve(m_chunk_size);
4210             if (m_chunk_size != 0) {
4211                 m_chunk.push_back(m_generator.get());
4212                 for (size_t i = 1; i < m_chunk_size; ++i) {
4213                     if (!m_generator.next()) {
4214                         Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4215                     }
4216                     m_chunk.push_back(m_generator.get());
4217                 }
4218             }
4219         }
get() const4220         std::vector<T> const& get() const override {
4221             return m_chunk;
4222         }
next()4223         bool next() override {
4224             m_chunk.clear();
4225             for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4226                 if (!m_generator.next()) {
4227                     return false;
4228                 }
4229                 m_chunk.push_back(m_generator.get());
4230             }
4231             return true;
4232         }
4233     };
4234 
4235     template <typename T>
chunk(size_t size,GeneratorWrapper<T> && generator)4236     GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4237         return GeneratorWrapper<std::vector<T>>(
4238             pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4239         );
4240     }
4241 
4242 } // namespace Generators
4243 } // namespace Catch
4244 
4245 // end catch_generators_generic.hpp
4246 // start catch_generators_specific.hpp
4247 
4248 // start catch_context.h
4249 
4250 #include <memory>
4251 
4252 namespace Catch {
4253 
4254     struct IResultCapture;
4255     struct IRunner;
4256     struct IConfig;
4257     struct IMutableContext;
4258 
4259     using IConfigPtr = std::shared_ptr<IConfig const>;
4260 
4261     struct IContext
4262     {
4263         virtual ~IContext();
4264 
4265         virtual IResultCapture* getResultCapture() = 0;
4266         virtual IRunner* getRunner() = 0;
4267         virtual IConfigPtr const& getConfig() const = 0;
4268     };
4269 
4270     struct IMutableContext : IContext
4271     {
4272         virtual ~IMutableContext();
4273         virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4274         virtual void setRunner( IRunner* runner ) = 0;
4275         virtual void setConfig( IConfigPtr const& config ) = 0;
4276 
4277     private:
4278         static IMutableContext *currentContext;
4279         friend IMutableContext& getCurrentMutableContext();
4280         friend void cleanUpContext();
4281         static void createContext();
4282     };
4283 
getCurrentMutableContext()4284     inline IMutableContext& getCurrentMutableContext()
4285     {
4286         if( !IMutableContext::currentContext )
4287             IMutableContext::createContext();
4288         return *IMutableContext::currentContext;
4289     }
4290 
getCurrentContext()4291     inline IContext& getCurrentContext()
4292     {
4293         return getCurrentMutableContext();
4294     }
4295 
4296     void cleanUpContext();
4297 }
4298 
4299 // end catch_context.h
4300 // start catch_interfaces_config.h
4301 
4302 // start catch_option.hpp
4303 
4304 namespace Catch {
4305 
4306     // An optional type
4307     template<typename T>
4308     class Option {
4309     public:
Option()4310         Option() : nullableValue( nullptr ) {}
Option(T const & _value)4311         Option( T const& _value )
4312         : nullableValue( new( storage ) T( _value ) )
4313         {}
Option(Option const & _other)4314         Option( Option const& _other )
4315         : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4316         {}
4317 
~Option()4318         ~Option() {
4319             reset();
4320         }
4321 
operator =(Option const & _other)4322         Option& operator= ( Option const& _other ) {
4323             if( &_other != this ) {
4324                 reset();
4325                 if( _other )
4326                     nullableValue = new( storage ) T( *_other );
4327             }
4328             return *this;
4329         }
operator =(T const & _value)4330         Option& operator = ( T const& _value ) {
4331             reset();
4332             nullableValue = new( storage ) T( _value );
4333             return *this;
4334         }
4335 
reset()4336         void reset() {
4337             if( nullableValue )
4338                 nullableValue->~T();
4339             nullableValue = nullptr;
4340         }
4341 
operator *()4342         T& operator*() { return *nullableValue; }
operator *() const4343         T const& operator*() const { return *nullableValue; }
operator ->()4344         T* operator->() { return nullableValue; }
operator ->() const4345         const T* operator->() const { return nullableValue; }
4346 
valueOr(T const & defaultValue) const4347         T valueOr( T const& defaultValue ) const {
4348             return nullableValue ? *nullableValue : defaultValue;
4349         }
4350 
some() const4351         bool some() const { return nullableValue != nullptr; }
none() const4352         bool none() const { return nullableValue == nullptr; }
4353 
operator !() const4354         bool operator !() const { return nullableValue == nullptr; }
operator bool() const4355         explicit operator bool() const {
4356             return some();
4357         }
4358 
4359     private:
4360         T *nullableValue;
4361         alignas(alignof(T)) char storage[sizeof(T)];
4362     };
4363 
4364 } // end namespace Catch
4365 
4366 // end catch_option.hpp
4367 #include <iosfwd>
4368 #include <string>
4369 #include <vector>
4370 #include <memory>
4371 
4372 namespace Catch {
4373 
4374     enum class Verbosity {
4375         Quiet = 0,
4376         Normal,
4377         High
4378     };
4379 
4380     struct WarnAbout { enum What {
4381         Nothing = 0x00,
4382         NoAssertions = 0x01,
4383         NoTests = 0x02
4384     }; };
4385 
4386     struct ShowDurations { enum OrNot {
4387         DefaultForReporter,
4388         Always,
4389         Never
4390     }; };
4391     struct RunTests { enum InWhatOrder {
4392         InDeclarationOrder,
4393         InLexicographicalOrder,
4394         InRandomOrder
4395     }; };
4396     struct UseColour { enum YesOrNo {
4397         Auto,
4398         Yes,
4399         No
4400     }; };
4401     struct WaitForKeypress { enum When {
4402         Never,
4403         BeforeStart = 1,
4404         BeforeExit = 2,
4405         BeforeStartAndExit = BeforeStart | BeforeExit
4406     }; };
4407 
4408     class TestSpec;
4409 
4410     struct IConfig : NonCopyable {
4411 
4412         virtual ~IConfig();
4413 
4414         virtual bool allowThrows() const = 0;
4415         virtual std::ostream& stream() const = 0;
4416         virtual std::string name() const = 0;
4417         virtual bool includeSuccessfulResults() const = 0;
4418         virtual bool shouldDebugBreak() const = 0;
4419         virtual bool warnAboutMissingAssertions() const = 0;
4420         virtual bool warnAboutNoTests() const = 0;
4421         virtual int abortAfter() const = 0;
4422         virtual bool showInvisibles() const = 0;
4423         virtual ShowDurations::OrNot showDurations() const = 0;
4424         virtual TestSpec const& testSpec() const = 0;
4425         virtual bool hasTestFilters() const = 0;
4426         virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4427         virtual RunTests::InWhatOrder runOrder() const = 0;
4428         virtual unsigned int rngSeed() const = 0;
4429         virtual UseColour::YesOrNo useColour() const = 0;
4430         virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4431         virtual Verbosity verbosity() const = 0;
4432 
4433         virtual bool benchmarkNoAnalysis() const = 0;
4434         virtual int benchmarkSamples() const = 0;
4435         virtual double benchmarkConfidenceInterval() const = 0;
4436         virtual unsigned int benchmarkResamples() const = 0;
4437     };
4438 
4439     using IConfigPtr = std::shared_ptr<IConfig const>;
4440 }
4441 
4442 // end catch_interfaces_config.h
4443 #include <random>
4444 
4445 namespace Catch {
4446 namespace Generators {
4447 
4448 template <typename Float>
4449 class RandomFloatingGenerator final : public IGenerator<Float> {
4450     // FIXME: What is the right seed?
4451     std::minstd_rand m_rand;
4452     std::uniform_real_distribution<Float> m_dist;
4453     Float m_current_number;
4454 public:
4455 
RandomFloatingGenerator(Float a,Float b)4456     RandomFloatingGenerator(Float a, Float b):
4457         m_rand(getCurrentContext().getConfig()->rngSeed()),
4458         m_dist(a, b) {
4459         static_cast<void>(next());
4460     }
4461 
get() const4462     Float const& get() const override {
4463         return m_current_number;
4464     }
next()4465     bool next() override {
4466         m_current_number = m_dist(m_rand);
4467         return true;
4468     }
4469 };
4470 
4471 template <typename Integer>
4472 class RandomIntegerGenerator final : public IGenerator<Integer> {
4473     std::minstd_rand m_rand;
4474     std::uniform_int_distribution<Integer> m_dist;
4475     Integer m_current_number;
4476 public:
4477 
RandomIntegerGenerator(Integer a,Integer b)4478     RandomIntegerGenerator(Integer a, Integer b):
4479         m_rand(getCurrentContext().getConfig()->rngSeed()),
4480         m_dist(a, b) {
4481         static_cast<void>(next());
4482     }
4483 
get() const4484     Integer const& get() const override {
4485         return m_current_number;
4486     }
next()4487     bool next() override {
4488         m_current_number = m_dist(m_rand);
4489         return true;
4490     }
4491 };
4492 
4493 // TODO: Ideally this would be also constrained against the various char types,
4494 //       but I don't expect users to run into that in practice.
4495 template <typename T>
4496 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4497 GeneratorWrapper<T>>::type
random(T a,T b)4498 random(T a, T b) {
4499     return GeneratorWrapper<T>(
4500         pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4501     );
4502 }
4503 
4504 template <typename T>
4505 typename std::enable_if<std::is_floating_point<T>::value,
4506 GeneratorWrapper<T>>::type
random(T a,T b)4507 random(T a, T b) {
4508     return GeneratorWrapper<T>(
4509         pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4510     );
4511 }
4512 
4513 template <typename T>
4514 class RangeGenerator final : public IGenerator<T> {
4515     T m_current;
4516     T m_end;
4517     T m_step;
4518     bool m_positive;
4519 
4520 public:
RangeGenerator(T const & start,T const & end,T const & step)4521     RangeGenerator(T const& start, T const& end, T const& step):
4522         m_current(start),
4523         m_end(end),
4524         m_step(step),
4525         m_positive(m_step > T(0))
4526     {
4527         assert(m_current != m_end && "Range start and end cannot be equal");
4528         assert(m_step != T(0) && "Step size cannot be zero");
4529         assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4530     }
4531 
RangeGenerator(T const & start,T const & end)4532     RangeGenerator(T const& start, T const& end):
4533         RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4534     {}
4535 
get() const4536     T const& get() const override {
4537         return m_current;
4538     }
4539 
next()4540     bool next() override {
4541         m_current += m_step;
4542         return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4543     }
4544 };
4545 
4546 template <typename T>
range(T const & start,T const & end,T const & step)4547 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4548     static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4549     return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4550 }
4551 
4552 template <typename T>
range(T const & start,T const & end)4553 GeneratorWrapper<T> range(T const& start, T const& end) {
4554     static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4555     return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4556 }
4557 
4558 } // namespace Generators
4559 } // namespace Catch
4560 
4561 // end catch_generators_specific.hpp
4562 
4563 // These files are included here so the single_include script doesn't put them
4564 // in the conditionally compiled sections
4565 // start catch_test_case_info.h
4566 
4567 #include <string>
4568 #include <vector>
4569 #include <memory>
4570 
4571 #ifdef __clang__
4572 #pragma clang diagnostic push
4573 #pragma clang diagnostic ignored "-Wpadded"
4574 #endif
4575 
4576 namespace Catch {
4577 
4578     struct ITestInvoker;
4579 
4580     struct TestCaseInfo {
4581         enum SpecialProperties{
4582             None = 0,
4583             IsHidden = 1 << 1,
4584             ShouldFail = 1 << 2,
4585             MayFail = 1 << 3,
4586             Throws = 1 << 4,
4587             NonPortable = 1 << 5,
4588             Benchmark = 1 << 6
4589         };
4590 
4591         TestCaseInfo(   std::string const& _name,
4592                         std::string const& _className,
4593                         std::string const& _description,
4594                         std::vector<std::string> const& _tags,
4595                         SourceLineInfo const& _lineInfo );
4596 
4597         friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4598 
4599         bool isHidden() const;
4600         bool throws() const;
4601         bool okToFail() const;
4602         bool expectedToFail() const;
4603 
4604         std::string tagsAsString() const;
4605 
4606         std::string name;
4607         std::string className;
4608         std::string description;
4609         std::vector<std::string> tags;
4610         std::vector<std::string> lcaseTags;
4611         SourceLineInfo lineInfo;
4612         SpecialProperties properties;
4613     };
4614 
4615     class TestCase : public TestCaseInfo {
4616     public:
4617 
4618         TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4619 
4620         TestCase withName( std::string const& _newName ) const;
4621 
4622         void invoke() const;
4623 
4624         TestCaseInfo const& getTestCaseInfo() const;
4625 
4626         bool operator == ( TestCase const& other ) const;
4627         bool operator < ( TestCase const& other ) const;
4628 
4629     private:
4630         std::shared_ptr<ITestInvoker> test;
4631     };
4632 
4633     TestCase makeTestCase(  ITestInvoker* testCase,
4634                             std::string const& className,
4635                             NameAndTags const& nameAndTags,
4636                             SourceLineInfo const& lineInfo );
4637 }
4638 
4639 #ifdef __clang__
4640 #pragma clang diagnostic pop
4641 #endif
4642 
4643 // end catch_test_case_info.h
4644 // start catch_interfaces_runner.h
4645 
4646 namespace Catch {
4647 
4648     struct IRunner {
4649         virtual ~IRunner();
4650         virtual bool aborting() const = 0;
4651     };
4652 }
4653 
4654 // end catch_interfaces_runner.h
4655 
4656 #ifdef __OBJC__
4657 // start catch_objc.hpp
4658 
4659 #import <objc/runtime.h>
4660 
4661 #include <string>
4662 
4663 // NB. Any general catch headers included here must be included
4664 // in catch.hpp first to make sure they are included by the single
4665 // header for non obj-usage
4666 
4667 ///////////////////////////////////////////////////////////////////////////////
4668 // This protocol is really only here for (self) documenting purposes, since
4669 // all its methods are optional.
4670 @protocol OcFixture
4671 
4672 @optional
4673 
4674 -(void) setUp;
4675 -(void) tearDown;
4676 
4677 @end
4678 
4679 namespace Catch {
4680 
4681     class OcMethod : public ITestInvoker {
4682 
4683     public:
OcMethod(Class cls,SEL sel)4684         OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4685 
invoke() const4686         virtual void invoke() const {
4687             id obj = [[m_cls alloc] init];
4688 
4689             performOptionalSelector( obj, @selector(setUp)  );
4690             performOptionalSelector( obj, m_sel );
4691             performOptionalSelector( obj, @selector(tearDown)  );
4692 
4693             arcSafeRelease( obj );
4694         }
4695     private:
~OcMethod()4696         virtual ~OcMethod() {}
4697 
4698         Class m_cls;
4699         SEL m_sel;
4700     };
4701 
4702     namespace Detail{
4703 
getAnnotation(Class cls,std::string const & annotationName,std::string const & testCaseName)4704         inline std::string getAnnotation(   Class cls,
4705                                             std::string const& annotationName,
4706                                             std::string const& testCaseName ) {
4707             NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4708             SEL sel = NSSelectorFromString( selStr );
4709             arcSafeRelease( selStr );
4710             id value = performOptionalSelector( cls, sel );
4711             if( value )
4712                 return [(NSString*)value UTF8String];
4713             return "";
4714         }
4715     }
4716 
registerTestMethods()4717     inline std::size_t registerTestMethods() {
4718         std::size_t noTestMethods = 0;
4719         int noClasses = objc_getClassList( nullptr, 0 );
4720 
4721         Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4722         objc_getClassList( classes, noClasses );
4723 
4724         for( int c = 0; c < noClasses; c++ ) {
4725             Class cls = classes[c];
4726             {
4727                 u_int count;
4728                 Method* methods = class_copyMethodList( cls, &count );
4729                 for( u_int m = 0; m < count ; m++ ) {
4730                     SEL selector = method_getName(methods[m]);
4731                     std::string methodName = sel_getName(selector);
4732                     if( startsWith( methodName, "Catch_TestCase_" ) ) {
4733                         std::string testCaseName = methodName.substr( 15 );
4734                         std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4735                         std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4736                         const char* className = class_getName( cls );
4737 
4738                         getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4739                         noTestMethods++;
4740                     }
4741                 }
4742                 free(methods);
4743             }
4744         }
4745         return noTestMethods;
4746     }
4747 
4748 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4749 
4750     namespace Matchers {
4751         namespace Impl {
4752         namespace NSStringMatchers {
4753 
4754             struct StringHolder : MatcherBase<NSString*>{
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4755                 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4756                 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4757                 StringHolder() {
4758                     arcSafeRelease( m_substr );
4759                 }
4760 
matchCatch::Matchers::Impl::NSStringMatchers::StringHolder4761                 bool match( NSString* str ) const override {
4762                     return false;
4763                 }
4764 
4765                 NSString* CATCH_ARC_STRONG m_substr;
4766             };
4767 
4768             struct Equals : StringHolder {
EqualsCatch::Matchers::Impl::NSStringMatchers::Equals4769                 Equals( NSString* substr ) : StringHolder( substr ){}
4770 
matchCatch::Matchers::Impl::NSStringMatchers::Equals4771                 bool match( NSString* str ) const override {
4772                     return  (str != nil || m_substr == nil ) &&
4773                             [str isEqualToString:m_substr];
4774                 }
4775 
describeCatch::Matchers::Impl::NSStringMatchers::Equals4776                 std::string describe() const override {
4777                     return "equals string: " + Catch::Detail::stringify( m_substr );
4778                 }
4779             };
4780 
4781             struct Contains : StringHolder {
ContainsCatch::Matchers::Impl::NSStringMatchers::Contains4782                 Contains( NSString* substr ) : StringHolder( substr ){}
4783 
matchCatch::Matchers::Impl::NSStringMatchers::Contains4784                 bool match( NSString* str ) const override {
4785                     return  (str != nil || m_substr == nil ) &&
4786                             [str rangeOfString:m_substr].location != NSNotFound;
4787                 }
4788 
describeCatch::Matchers::Impl::NSStringMatchers::Contains4789                 std::string describe() const override {
4790                     return "contains string: " + Catch::Detail::stringify( m_substr );
4791                 }
4792             };
4793 
4794             struct StartsWith : StringHolder {
StartsWithCatch::Matchers::Impl::NSStringMatchers::StartsWith4795                 StartsWith( NSString* substr ) : StringHolder( substr ){}
4796 
matchCatch::Matchers::Impl::NSStringMatchers::StartsWith4797                 bool match( NSString* str ) const override {
4798                     return  (str != nil || m_substr == nil ) &&
4799                             [str rangeOfString:m_substr].location == 0;
4800                 }
4801 
describeCatch::Matchers::Impl::NSStringMatchers::StartsWith4802                 std::string describe() const override {
4803                     return "starts with: " + Catch::Detail::stringify( m_substr );
4804                 }
4805             };
4806             struct EndsWith : StringHolder {
EndsWithCatch::Matchers::Impl::NSStringMatchers::EndsWith4807                 EndsWith( NSString* substr ) : StringHolder( substr ){}
4808 
matchCatch::Matchers::Impl::NSStringMatchers::EndsWith4809                 bool match( NSString* str ) const override {
4810                     return  (str != nil || m_substr == nil ) &&
4811                             [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4812                 }
4813 
describeCatch::Matchers::Impl::NSStringMatchers::EndsWith4814                 std::string describe() const override {
4815                     return "ends with: " + Catch::Detail::stringify( m_substr );
4816                 }
4817             };
4818 
4819         } // namespace NSStringMatchers
4820         } // namespace Impl
4821 
4822         inline Impl::NSStringMatchers::Equals
Equals(NSString * substr)4823             Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
4824 
4825         inline Impl::NSStringMatchers::Contains
Contains(NSString * substr)4826             Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
4827 
4828         inline Impl::NSStringMatchers::StartsWith
StartsWith(NSString * substr)4829             StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
4830 
4831         inline Impl::NSStringMatchers::EndsWith
EndsWith(NSString * substr)4832             EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
4833 
4834     } // namespace Matchers
4835 
4836     using namespace Matchers;
4837 
4838 #endif // CATCH_CONFIG_DISABLE_MATCHERS
4839 
4840 } // namespace Catch
4841 
4842 ///////////////////////////////////////////////////////////////////////////////
4843 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
4844 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
4845 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
4846 { \
4847 return @ name; \
4848 } \
4849 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
4850 { \
4851 return @ desc; \
4852 } \
4853 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
4854 
4855 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
4856 
4857 // end catch_objc.hpp
4858 #endif
4859 
4860 // Benchmarking needs the externally-facing parts of reporters to work
4861 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
4862 // start catch_external_interfaces.h
4863 
4864 // start catch_reporter_bases.hpp
4865 
4866 // start catch_interfaces_reporter.h
4867 
4868 // start catch_config.hpp
4869 
4870 // start catch_test_spec_parser.h
4871 
4872 #ifdef __clang__
4873 #pragma clang diagnostic push
4874 #pragma clang diagnostic ignored "-Wpadded"
4875 #endif
4876 
4877 // start catch_test_spec.h
4878 
4879 #ifdef __clang__
4880 #pragma clang diagnostic push
4881 #pragma clang diagnostic ignored "-Wpadded"
4882 #endif
4883 
4884 // start catch_wildcard_pattern.h
4885 
4886 namespace Catch
4887 {
4888     class WildcardPattern {
4889         enum WildcardPosition {
4890             NoWildcard = 0,
4891             WildcardAtStart = 1,
4892             WildcardAtEnd = 2,
4893             WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
4894         };
4895 
4896     public:
4897 
4898         WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
4899         virtual ~WildcardPattern() = default;
4900         virtual bool matches( std::string const& str ) const;
4901 
4902     private:
4903         std::string adjustCase( std::string const& str ) const;
4904         CaseSensitive::Choice m_caseSensitivity;
4905         WildcardPosition m_wildcard = NoWildcard;
4906         std::string m_pattern;
4907     };
4908 }
4909 
4910 // end catch_wildcard_pattern.h
4911 #include <string>
4912 #include <vector>
4913 #include <memory>
4914 
4915 namespace Catch {
4916 
4917     struct IConfig;
4918 
4919     class TestSpec {
4920         class Pattern {
4921         public:
4922             explicit Pattern( std::string const& name );
4923             virtual ~Pattern();
4924             virtual bool matches( TestCaseInfo const& testCase ) const = 0;
4925             std::string const& name() const;
4926         private:
4927             std::string const m_name;
4928         };
4929         using PatternPtr = std::shared_ptr<Pattern>;
4930 
4931         class NamePattern : public Pattern {
4932         public:
4933             explicit NamePattern( std::string const& name, std::string const& filterString );
4934             bool matches( TestCaseInfo const& testCase ) const override;
4935         private:
4936             WildcardPattern m_wildcardPattern;
4937         };
4938 
4939         class TagPattern : public Pattern {
4940         public:
4941             explicit TagPattern( std::string const& tag, std::string const& filterString );
4942             bool matches( TestCaseInfo const& testCase ) const override;
4943         private:
4944             std::string m_tag;
4945         };
4946 
4947         class ExcludedPattern : public Pattern {
4948         public:
4949             explicit ExcludedPattern( PatternPtr const& underlyingPattern );
4950             bool matches( TestCaseInfo const& testCase ) const override;
4951         private:
4952             PatternPtr m_underlyingPattern;
4953         };
4954 
4955         struct Filter {
4956             std::vector<PatternPtr> m_patterns;
4957 
4958             bool matches( TestCaseInfo const& testCase ) const;
4959             std::string name() const;
4960         };
4961 
4962     public:
4963         struct FilterMatch {
4964             std::string name;
4965             std::vector<TestCase const*> tests;
4966         };
4967         using Matches = std::vector<FilterMatch>;
4968 
4969         bool hasFilters() const;
4970         bool matches( TestCaseInfo const& testCase ) const;
4971         Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
4972 
4973     private:
4974         std::vector<Filter> m_filters;
4975 
4976         friend class TestSpecParser;
4977     };
4978 }
4979 
4980 #ifdef __clang__
4981 #pragma clang diagnostic pop
4982 #endif
4983 
4984 // end catch_test_spec.h
4985 // start catch_interfaces_tag_alias_registry.h
4986 
4987 #include <string>
4988 
4989 namespace Catch {
4990 
4991     struct TagAlias;
4992 
4993     struct ITagAliasRegistry {
4994         virtual ~ITagAliasRegistry();
4995         // Nullptr if not present
4996         virtual TagAlias const* find( std::string const& alias ) const = 0;
4997         virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
4998 
4999         static ITagAliasRegistry const& get();
5000     };
5001 
5002 } // end namespace Catch
5003 
5004 // end catch_interfaces_tag_alias_registry.h
5005 namespace Catch {
5006 
5007     class TestSpecParser {
5008         enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5009         Mode m_mode = None;
5010         bool m_exclusion = false;
5011         std::size_t m_pos = 0;
5012         std::string m_arg;
5013         std::string m_substring;
5014         std::string m_patternName;
5015         std::vector<std::size_t> m_escapeChars;
5016         TestSpec::Filter m_currentFilter;
5017         TestSpec m_testSpec;
5018         ITagAliasRegistry const* m_tagAliases = nullptr;
5019 
5020     public:
5021         TestSpecParser( ITagAliasRegistry const& tagAliases );
5022 
5023         TestSpecParser& parse( std::string const& arg );
5024         TestSpec testSpec();
5025 
5026     private:
5027         void visitChar( char c );
5028         void startNewMode( Mode mode );
5029         bool processNoneChar( char c );
5030         void processNameChar( char c );
5031         bool processOtherChar( char c );
5032         void endMode();
5033         void escape();
5034         bool isControlChar( char c ) const;
5035 
5036         template<typename T>
addPattern()5037         void addPattern() {
5038             std::string token = m_patternName;
5039             for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
5040                 token = token.substr( 0, m_escapeChars[i] - i ) + token.substr( m_escapeChars[i] -i +1 );
5041             m_escapeChars.clear();
5042             if( startsWith( token, "exclude:" ) ) {
5043                 m_exclusion = true;
5044                 token = token.substr( 8 );
5045             }
5046             if( !token.empty() ) {
5047                 TestSpec::PatternPtr pattern = std::make_shared<T>( token, m_substring );
5048                 if( m_exclusion )
5049                     pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
5050                 m_currentFilter.m_patterns.push_back( pattern );
5051             }
5052             m_substring.clear();
5053             m_patternName.clear();
5054             m_exclusion = false;
5055             m_mode = None;
5056         }
5057 
5058         void addFilter();
5059     };
5060     TestSpec parseTestSpec( std::string const& arg );
5061 
5062 } // namespace Catch
5063 
5064 #ifdef __clang__
5065 #pragma clang diagnostic pop
5066 #endif
5067 
5068 // end catch_test_spec_parser.h
5069 // Libstdc++ doesn't like incomplete classes for unique_ptr
5070 
5071 #include <memory>
5072 #include <vector>
5073 #include <string>
5074 
5075 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5076 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5077 #endif
5078 
5079 namespace Catch {
5080 
5081     struct IStream;
5082 
5083     struct ConfigData {
5084         bool listTests = false;
5085         bool listTags = false;
5086         bool listReporters = false;
5087         bool listTestNamesOnly = false;
5088 
5089         bool showSuccessfulTests = false;
5090         bool shouldDebugBreak = false;
5091         bool noThrow = false;
5092         bool showHelp = false;
5093         bool showInvisibles = false;
5094         bool filenamesAsTags = false;
5095         bool libIdentify = false;
5096 
5097         int abortAfter = -1;
5098         unsigned int rngSeed = 0;
5099 
5100         bool benchmarkNoAnalysis = false;
5101         unsigned int benchmarkSamples = 100;
5102         double benchmarkConfidenceInterval = 0.95;
5103         unsigned int benchmarkResamples = 100000;
5104 
5105         Verbosity verbosity = Verbosity::Normal;
5106         WarnAbout::What warnings = WarnAbout::Nothing;
5107         ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5108         RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5109         UseColour::YesOrNo useColour = UseColour::Auto;
5110         WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5111 
5112         std::string outputFilename;
5113         std::string name;
5114         std::string processName;
5115 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5116 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5117 #endif
5118         std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5119 #undef CATCH_CONFIG_DEFAULT_REPORTER
5120 
5121         std::vector<std::string> testsOrTags;
5122         std::vector<std::string> sectionsToRun;
5123     };
5124 
5125     class Config : public IConfig {
5126     public:
5127 
5128         Config() = default;
5129         Config( ConfigData const& data );
5130         virtual ~Config() = default;
5131 
5132         std::string const& getFilename() const;
5133 
5134         bool listTests() const;
5135         bool listTestNamesOnly() const;
5136         bool listTags() const;
5137         bool listReporters() const;
5138 
5139         std::string getProcessName() const;
5140         std::string const& getReporterName() const;
5141 
5142         std::vector<std::string> const& getTestsOrTags() const override;
5143         std::vector<std::string> const& getSectionsToRun() const override;
5144 
5145         TestSpec const& testSpec() const override;
5146         bool hasTestFilters() const override;
5147 
5148         bool showHelp() const;
5149 
5150         // IConfig interface
5151         bool allowThrows() const override;
5152         std::ostream& stream() const override;
5153         std::string name() const override;
5154         bool includeSuccessfulResults() const override;
5155         bool warnAboutMissingAssertions() const override;
5156         bool warnAboutNoTests() const override;
5157         ShowDurations::OrNot showDurations() const override;
5158         RunTests::InWhatOrder runOrder() const override;
5159         unsigned int rngSeed() const override;
5160         UseColour::YesOrNo useColour() const override;
5161         bool shouldDebugBreak() const override;
5162         int abortAfter() const override;
5163         bool showInvisibles() const override;
5164         Verbosity verbosity() const override;
5165         bool benchmarkNoAnalysis() const override;
5166         int benchmarkSamples() const override;
5167         double benchmarkConfidenceInterval() const override;
5168         unsigned int benchmarkResamples() const override;
5169 
5170     private:
5171 
5172         IStream const* openStream();
5173         ConfigData m_data;
5174 
5175         std::unique_ptr<IStream const> m_stream;
5176         TestSpec m_testSpec;
5177         bool m_hasTestFilters = false;
5178     };
5179 
5180 } // end namespace Catch
5181 
5182 // end catch_config.hpp
5183 // start catch_assertionresult.h
5184 
5185 #include <string>
5186 
5187 namespace Catch {
5188 
5189     struct AssertionResultData
5190     {
5191         AssertionResultData() = delete;
5192 
5193         AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5194 
5195         std::string message;
5196         mutable std::string reconstructedExpression;
5197         LazyExpression lazyExpression;
5198         ResultWas::OfType resultType;
5199 
5200         std::string reconstructExpression() const;
5201     };
5202 
5203     class AssertionResult {
5204     public:
5205         AssertionResult() = delete;
5206         AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5207 
5208         bool isOk() const;
5209         bool succeeded() const;
5210         ResultWas::OfType getResultType() const;
5211         bool hasExpression() const;
5212         bool hasMessage() const;
5213         std::string getExpression() const;
5214         std::string getExpressionInMacro() const;
5215         bool hasExpandedExpression() const;
5216         std::string getExpandedExpression() const;
5217         std::string getMessage() const;
5218         SourceLineInfo getSourceInfo() const;
5219         StringRef getTestMacroName() const;
5220 
5221     //protected:
5222         AssertionInfo m_info;
5223         AssertionResultData m_resultData;
5224     };
5225 
5226 } // end namespace Catch
5227 
5228 // end catch_assertionresult.h
5229 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5230 // start catch_estimate.hpp
5231 
5232  // Statistics estimates
5233 
5234 
5235 namespace Catch {
5236     namespace Benchmark {
5237         template <typename Duration>
5238         struct Estimate {
5239             Duration point;
5240             Duration lower_bound;
5241             Duration upper_bound;
5242             double confidence_interval;
5243 
5244             template <typename Duration2>
operator Estimate<Duration2>Catch::Benchmark::Estimate5245             operator Estimate<Duration2>() const {
5246                 return { point, lower_bound, upper_bound, confidence_interval };
5247             }
5248         };
5249     } // namespace Benchmark
5250 } // namespace Catch
5251 
5252 // end catch_estimate.hpp
5253 // start catch_outlier_classification.hpp
5254 
5255 // Outlier information
5256 
5257 namespace Catch {
5258     namespace Benchmark {
5259         struct OutlierClassification {
5260             int samples_seen = 0;
5261             int low_severe = 0;     // more than 3 times IQR below Q1
5262             int low_mild = 0;       // 1.5 to 3 times IQR below Q1
5263             int high_mild = 0;      // 1.5 to 3 times IQR above Q3
5264             int high_severe = 0;    // more than 3 times IQR above Q3
5265 
totalCatch::Benchmark::OutlierClassification5266             int total() const {
5267                 return low_severe + low_mild + high_mild + high_severe;
5268             }
5269         };
5270     } // namespace Benchmark
5271 } // namespace Catch
5272 
5273 // end catch_outlier_classification.hpp
5274 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5275 
5276 #include <string>
5277 #include <iosfwd>
5278 #include <map>
5279 #include <set>
5280 #include <memory>
5281 #include <algorithm>
5282 
5283 namespace Catch {
5284 
5285     struct ReporterConfig {
5286         explicit ReporterConfig( IConfigPtr const& _fullConfig );
5287 
5288         ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5289 
5290         std::ostream& stream() const;
5291         IConfigPtr fullConfig() const;
5292 
5293     private:
5294         std::ostream* m_stream;
5295         IConfigPtr m_fullConfig;
5296     };
5297 
5298     struct ReporterPreferences {
5299         bool shouldRedirectStdOut = false;
5300         bool shouldReportAllAssertions = false;
5301     };
5302 
5303     template<typename T>
5304     struct LazyStat : Option<T> {
operator =Catch::LazyStat5305         LazyStat& operator=( T const& _value ) {
5306             Option<T>::operator=( _value );
5307             used = false;
5308             return *this;
5309         }
resetCatch::LazyStat5310         void reset() {
5311             Option<T>::reset();
5312             used = false;
5313         }
5314         bool used = false;
5315     };
5316 
5317     struct TestRunInfo {
5318         TestRunInfo( std::string const& _name );
5319         std::string name;
5320     };
5321     struct GroupInfo {
5322         GroupInfo(  std::string const& _name,
5323                     std::size_t _groupIndex,
5324                     std::size_t _groupsCount );
5325 
5326         std::string name;
5327         std::size_t groupIndex;
5328         std::size_t groupsCounts;
5329     };
5330 
5331     struct AssertionStats {
5332         AssertionStats( AssertionResult const& _assertionResult,
5333                         std::vector<MessageInfo> const& _infoMessages,
5334                         Totals const& _totals );
5335 
5336         AssertionStats( AssertionStats const& )              = default;
5337         AssertionStats( AssertionStats && )                  = default;
5338         AssertionStats& operator = ( AssertionStats const& ) = delete;
5339         AssertionStats& operator = ( AssertionStats && )     = delete;
5340         virtual ~AssertionStats();
5341 
5342         AssertionResult assertionResult;
5343         std::vector<MessageInfo> infoMessages;
5344         Totals totals;
5345     };
5346 
5347     struct SectionStats {
5348         SectionStats(   SectionInfo const& _sectionInfo,
5349                         Counts const& _assertions,
5350                         double _durationInSeconds,
5351                         bool _missingAssertions );
5352         SectionStats( SectionStats const& )              = default;
5353         SectionStats( SectionStats && )                  = default;
5354         SectionStats& operator = ( SectionStats const& ) = default;
5355         SectionStats& operator = ( SectionStats && )     = default;
5356         virtual ~SectionStats();
5357 
5358         SectionInfo sectionInfo;
5359         Counts assertions;
5360         double durationInSeconds;
5361         bool missingAssertions;
5362     };
5363 
5364     struct TestCaseStats {
5365         TestCaseStats(  TestCaseInfo const& _testInfo,
5366                         Totals const& _totals,
5367                         std::string const& _stdOut,
5368                         std::string const& _stdErr,
5369                         bool _aborting );
5370 
5371         TestCaseStats( TestCaseStats const& )              = default;
5372         TestCaseStats( TestCaseStats && )                  = default;
5373         TestCaseStats& operator = ( TestCaseStats const& ) = default;
5374         TestCaseStats& operator = ( TestCaseStats && )     = default;
5375         virtual ~TestCaseStats();
5376 
5377         TestCaseInfo testInfo;
5378         Totals totals;
5379         std::string stdOut;
5380         std::string stdErr;
5381         bool aborting;
5382     };
5383 
5384     struct TestGroupStats {
5385         TestGroupStats( GroupInfo const& _groupInfo,
5386                         Totals const& _totals,
5387                         bool _aborting );
5388         TestGroupStats( GroupInfo const& _groupInfo );
5389 
5390         TestGroupStats( TestGroupStats const& )              = default;
5391         TestGroupStats( TestGroupStats && )                  = default;
5392         TestGroupStats& operator = ( TestGroupStats const& ) = default;
5393         TestGroupStats& operator = ( TestGroupStats && )     = default;
5394         virtual ~TestGroupStats();
5395 
5396         GroupInfo groupInfo;
5397         Totals totals;
5398         bool aborting;
5399     };
5400 
5401     struct TestRunStats {
5402         TestRunStats(   TestRunInfo const& _runInfo,
5403                         Totals const& _totals,
5404                         bool _aborting );
5405 
5406         TestRunStats( TestRunStats const& )              = default;
5407         TestRunStats( TestRunStats && )                  = default;
5408         TestRunStats& operator = ( TestRunStats const& ) = default;
5409         TestRunStats& operator = ( TestRunStats && )     = default;
5410         virtual ~TestRunStats();
5411 
5412         TestRunInfo runInfo;
5413         Totals totals;
5414         bool aborting;
5415     };
5416 
5417 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5418     struct BenchmarkInfo {
5419         std::string name;
5420         double estimatedDuration;
5421         int iterations;
5422         int samples;
5423         unsigned int resamples;
5424         double clockResolution;
5425         double clockCost;
5426     };
5427 
5428     template <class Duration>
5429     struct BenchmarkStats {
5430         BenchmarkInfo info;
5431 
5432         std::vector<Duration> samples;
5433         Benchmark::Estimate<Duration> mean;
5434         Benchmark::Estimate<Duration> standardDeviation;
5435         Benchmark::OutlierClassification outliers;
5436         double outlierVariance;
5437 
5438         template <typename Duration2>
operator BenchmarkStats<Duration2>Catch::BenchmarkStats5439         operator BenchmarkStats<Duration2>() const {
5440             std::vector<Duration2> samples2;
5441             samples2.reserve(samples.size());
5442             std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5443             return {
5444                 info,
5445                 std::move(samples2),
5446                 mean,
5447                 standardDeviation,
5448                 outliers,
5449                 outlierVariance,
5450             };
5451         }
5452     };
5453 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5454 
5455     struct IStreamingReporter {
5456         virtual ~IStreamingReporter() = default;
5457 
5458         // Implementing class must also provide the following static methods:
5459         // static std::string getDescription();
5460         // static std::set<Verbosity> getSupportedVerbosities()
5461 
5462         virtual ReporterPreferences getPreferences() const = 0;
5463 
5464         virtual void noMatchingTestCases( std::string const& spec ) = 0;
5465 
5466         virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5467         virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5468 
5469         virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5470         virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5471 
5472 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparingCatch::IStreamingReporter5473         virtual void benchmarkPreparing( std::string const& ) {}
benchmarkStartingCatch::IStreamingReporter5474         virtual void benchmarkStarting( BenchmarkInfo const& ) {}
benchmarkEndedCatch::IStreamingReporter5475         virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
benchmarkFailedCatch::IStreamingReporter5476         virtual void benchmarkFailed( std::string const& ) {}
5477 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5478 
5479         virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5480 
5481         // The return value indicates if the messages buffer should be cleared:
5482         virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5483 
5484         virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5485         virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5486         virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5487         virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5488 
5489         virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5490 
5491         // Default empty implementation provided
5492         virtual void fatalErrorEncountered( StringRef name );
5493 
5494         virtual bool isMulti() const;
5495     };
5496     using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5497 
5498     struct IReporterFactory {
5499         virtual ~IReporterFactory();
5500         virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5501         virtual std::string getDescription() const = 0;
5502     };
5503     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5504 
5505     struct IReporterRegistry {
5506         using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5507         using Listeners = std::vector<IReporterFactoryPtr>;
5508 
5509         virtual ~IReporterRegistry();
5510         virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5511         virtual FactoryMap const& getFactories() const = 0;
5512         virtual Listeners const& getListeners() const = 0;
5513     };
5514 
5515 } // end namespace Catch
5516 
5517 // end catch_interfaces_reporter.h
5518 #include <algorithm>
5519 #include <cstring>
5520 #include <cfloat>
5521 #include <cstdio>
5522 #include <cassert>
5523 #include <memory>
5524 #include <ostream>
5525 
5526 namespace Catch {
5527     void prepareExpandedExpression(AssertionResult& result);
5528 
5529     // Returns double formatted as %.3f (format expected on output)
5530     std::string getFormattedDuration( double duration );
5531 
5532     std::string serializeFilters( std::vector<std::string> const& container );
5533 
5534     template<typename DerivedT>
5535     struct StreamingReporterBase : IStreamingReporter {
5536 
StreamingReporterBaseCatch::StreamingReporterBase5537         StreamingReporterBase( ReporterConfig const& _config )
5538         :   m_config( _config.fullConfig() ),
5539             stream( _config.stream() )
5540         {
5541             m_reporterPrefs.shouldRedirectStdOut = false;
5542             if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5543                 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5544         }
5545 
getPreferencesCatch::StreamingReporterBase5546         ReporterPreferences getPreferences() const override {
5547             return m_reporterPrefs;
5548         }
5549 
getSupportedVerbositiesCatch::StreamingReporterBase5550         static std::set<Verbosity> getSupportedVerbosities() {
5551             return { Verbosity::Normal };
5552         }
5553 
5554         ~StreamingReporterBase() override = default;
5555 
noMatchingTestCasesCatch::StreamingReporterBase5556         void noMatchingTestCases(std::string const&) override {}
5557 
testRunStartingCatch::StreamingReporterBase5558         void testRunStarting(TestRunInfo const& _testRunInfo) override {
5559             currentTestRunInfo = _testRunInfo;
5560         }
5561 
testGroupStartingCatch::StreamingReporterBase5562         void testGroupStarting(GroupInfo const& _groupInfo) override {
5563             currentGroupInfo = _groupInfo;
5564         }
5565 
testCaseStartingCatch::StreamingReporterBase5566         void testCaseStarting(TestCaseInfo const& _testInfo) override  {
5567             currentTestCaseInfo = _testInfo;
5568         }
sectionStartingCatch::StreamingReporterBase5569         void sectionStarting(SectionInfo const& _sectionInfo) override {
5570             m_sectionStack.push_back(_sectionInfo);
5571         }
5572 
sectionEndedCatch::StreamingReporterBase5573         void sectionEnded(SectionStats const& /* _sectionStats */) override {
5574             m_sectionStack.pop_back();
5575         }
testCaseEndedCatch::StreamingReporterBase5576         void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5577             currentTestCaseInfo.reset();
5578         }
testGroupEndedCatch::StreamingReporterBase5579         void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5580             currentGroupInfo.reset();
5581         }
testRunEndedCatch::StreamingReporterBase5582         void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5583             currentTestCaseInfo.reset();
5584             currentGroupInfo.reset();
5585             currentTestRunInfo.reset();
5586         }
5587 
skipTestCatch::StreamingReporterBase5588         void skipTest(TestCaseInfo const&) override {
5589             // Don't do anything with this by default.
5590             // It can optionally be overridden in the derived class.
5591         }
5592 
5593         IConfigPtr m_config;
5594         std::ostream& stream;
5595 
5596         LazyStat<TestRunInfo> currentTestRunInfo;
5597         LazyStat<GroupInfo> currentGroupInfo;
5598         LazyStat<TestCaseInfo> currentTestCaseInfo;
5599 
5600         std::vector<SectionInfo> m_sectionStack;
5601         ReporterPreferences m_reporterPrefs;
5602     };
5603 
5604     template<typename DerivedT>
5605     struct CumulativeReporterBase : IStreamingReporter {
5606         template<typename T, typename ChildNodeT>
5607         struct Node {
NodeCatch::CumulativeReporterBase::Node5608             explicit Node( T const& _value ) : value( _value ) {}
~NodeCatch::CumulativeReporterBase::Node5609             virtual ~Node() {}
5610 
5611             using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5612             T value;
5613             ChildNodes children;
5614         };
5615         struct SectionNode {
SectionNodeCatch::CumulativeReporterBase::SectionNode5616             explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5617             virtual ~SectionNode() = default;
5618 
operator ==Catch::CumulativeReporterBase::SectionNode5619             bool operator == (SectionNode const& other) const {
5620                 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5621             }
operator ==Catch::CumulativeReporterBase::SectionNode5622             bool operator == (std::shared_ptr<SectionNode> const& other) const {
5623                 return operator==(*other);
5624             }
5625 
5626             SectionStats stats;
5627             using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5628             using Assertions = std::vector<AssertionStats>;
5629             ChildSections childSections;
5630             Assertions assertions;
5631             std::string stdOut;
5632             std::string stdErr;
5633         };
5634 
5635         struct BySectionInfo {
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5636             BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5637             BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
operator ()Catch::CumulativeReporterBase::BySectionInfo5638             bool operator() (std::shared_ptr<SectionNode> const& node) const {
5639                 return ((node->stats.sectionInfo.name == m_other.name) &&
5640                         (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5641             }
5642             void operator=(BySectionInfo const&) = delete;
5643 
5644         private:
5645             SectionInfo const& m_other;
5646         };
5647 
5648         using TestCaseNode = Node<TestCaseStats, SectionNode>;
5649         using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5650         using TestRunNode = Node<TestRunStats, TestGroupNode>;
5651 
CumulativeReporterBaseCatch::CumulativeReporterBase5652         CumulativeReporterBase( ReporterConfig const& _config )
5653         :   m_config( _config.fullConfig() ),
5654             stream( _config.stream() )
5655         {
5656             m_reporterPrefs.shouldRedirectStdOut = false;
5657             if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5658                 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5659         }
5660         ~CumulativeReporterBase() override = default;
5661 
getPreferencesCatch::CumulativeReporterBase5662         ReporterPreferences getPreferences() const override {
5663             return m_reporterPrefs;
5664         }
5665 
getSupportedVerbositiesCatch::CumulativeReporterBase5666         static std::set<Verbosity> getSupportedVerbosities() {
5667             return { Verbosity::Normal };
5668         }
5669 
testRunStartingCatch::CumulativeReporterBase5670         void testRunStarting( TestRunInfo const& ) override {}
testGroupStartingCatch::CumulativeReporterBase5671         void testGroupStarting( GroupInfo const& ) override {}
5672 
testCaseStartingCatch::CumulativeReporterBase5673         void testCaseStarting( TestCaseInfo const& ) override {}
5674 
sectionStartingCatch::CumulativeReporterBase5675         void sectionStarting( SectionInfo const& sectionInfo ) override {
5676             SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5677             std::shared_ptr<SectionNode> node;
5678             if( m_sectionStack.empty() ) {
5679                 if( !m_rootSection )
5680                     m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5681                 node = m_rootSection;
5682             }
5683             else {
5684                 SectionNode& parentNode = *m_sectionStack.back();
5685                 auto it =
5686                     std::find_if(   parentNode.childSections.begin(),
5687                                     parentNode.childSections.end(),
5688                                     BySectionInfo( sectionInfo ) );
5689                 if( it == parentNode.childSections.end() ) {
5690                     node = std::make_shared<SectionNode>( incompleteStats );
5691                     parentNode.childSections.push_back( node );
5692                 }
5693                 else
5694                     node = *it;
5695             }
5696             m_sectionStack.push_back( node );
5697             m_deepestSection = std::move(node);
5698         }
5699 
assertionStartingCatch::CumulativeReporterBase5700         void assertionStarting(AssertionInfo const&) override {}
5701 
assertionEndedCatch::CumulativeReporterBase5702         bool assertionEnded(AssertionStats const& assertionStats) override {
5703             assert(!m_sectionStack.empty());
5704             // AssertionResult holds a pointer to a temporary DecomposedExpression,
5705             // which getExpandedExpression() calls to build the expression string.
5706             // Our section stack copy of the assertionResult will likely outlive the
5707             // temporary, so it must be expanded or discarded now to avoid calling
5708             // a destroyed object later.
5709             prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5710             SectionNode& sectionNode = *m_sectionStack.back();
5711             sectionNode.assertions.push_back(assertionStats);
5712             return true;
5713         }
sectionEndedCatch::CumulativeReporterBase5714         void sectionEnded(SectionStats const& sectionStats) override {
5715             assert(!m_sectionStack.empty());
5716             SectionNode& node = *m_sectionStack.back();
5717             node.stats = sectionStats;
5718             m_sectionStack.pop_back();
5719         }
testCaseEndedCatch::CumulativeReporterBase5720         void testCaseEnded(TestCaseStats const& testCaseStats) override {
5721             auto node = std::make_shared<TestCaseNode>(testCaseStats);
5722             assert(m_sectionStack.size() == 0);
5723             node->children.push_back(m_rootSection);
5724             m_testCases.push_back(node);
5725             m_rootSection.reset();
5726 
5727             assert(m_deepestSection);
5728             m_deepestSection->stdOut = testCaseStats.stdOut;
5729             m_deepestSection->stdErr = testCaseStats.stdErr;
5730         }
testGroupEndedCatch::CumulativeReporterBase5731         void testGroupEnded(TestGroupStats const& testGroupStats) override {
5732             auto node = std::make_shared<TestGroupNode>(testGroupStats);
5733             node->children.swap(m_testCases);
5734             m_testGroups.push_back(node);
5735         }
testRunEndedCatch::CumulativeReporterBase5736         void testRunEnded(TestRunStats const& testRunStats) override {
5737             auto node = std::make_shared<TestRunNode>(testRunStats);
5738             node->children.swap(m_testGroups);
5739             m_testRuns.push_back(node);
5740             testRunEndedCumulative();
5741         }
5742         virtual void testRunEndedCumulative() = 0;
5743 
skipTestCatch::CumulativeReporterBase5744         void skipTest(TestCaseInfo const&) override {}
5745 
5746         IConfigPtr m_config;
5747         std::ostream& stream;
5748         std::vector<AssertionStats> m_assertions;
5749         std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5750         std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5751         std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5752 
5753         std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5754 
5755         std::shared_ptr<SectionNode> m_rootSection;
5756         std::shared_ptr<SectionNode> m_deepestSection;
5757         std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5758         ReporterPreferences m_reporterPrefs;
5759     };
5760 
5761     template<char C>
getLineOfChars()5762     char const* getLineOfChars() {
5763         static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5764         if( !*line ) {
5765             std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5766             line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5767         }
5768         return line;
5769     }
5770 
5771     struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5772         TestEventListenerBase( ReporterConfig const& _config );
5773 
5774         static std::set<Verbosity> getSupportedVerbosities();
5775 
5776         void assertionStarting(AssertionInfo const&) override;
5777         bool assertionEnded(AssertionStats const&) override;
5778     };
5779 
5780 } // end namespace Catch
5781 
5782 // end catch_reporter_bases.hpp
5783 // start catch_console_colour.h
5784 
5785 namespace Catch {
5786 
5787     struct Colour {
5788         enum Code {
5789             None = 0,
5790 
5791             White,
5792             Red,
5793             Green,
5794             Blue,
5795             Cyan,
5796             Yellow,
5797             Grey,
5798 
5799             Bright = 0x10,
5800 
5801             BrightRed = Bright | Red,
5802             BrightGreen = Bright | Green,
5803             LightGrey = Bright | Grey,
5804             BrightWhite = Bright | White,
5805             BrightYellow = Bright | Yellow,
5806 
5807             // By intention
5808             FileName = LightGrey,
5809             Warning = BrightYellow,
5810             ResultError = BrightRed,
5811             ResultSuccess = BrightGreen,
5812             ResultExpectedFailure = Warning,
5813 
5814             Error = BrightRed,
5815             Success = Green,
5816 
5817             OriginalExpression = Cyan,
5818             ReconstructedExpression = BrightYellow,
5819 
5820             SecondaryText = LightGrey,
5821             Headers = White
5822         };
5823 
5824         // Use constructed object for RAII guard
5825         Colour( Code _colourCode );
5826         Colour( Colour&& other ) noexcept;
5827         Colour& operator=( Colour&& other ) noexcept;
5828         ~Colour();
5829 
5830         // Use static method for one-shot changes
5831         static void use( Code _colourCode );
5832 
5833     private:
5834         bool m_moved = false;
5835     };
5836 
5837     std::ostream& operator << ( std::ostream& os, Colour const& );
5838 
5839 } // end namespace Catch
5840 
5841 // end catch_console_colour.h
5842 // start catch_reporter_registrars.hpp
5843 
5844 
5845 namespace Catch {
5846 
5847     template<typename T>
5848     class ReporterRegistrar {
5849 
5850         class ReporterFactory : public IReporterFactory {
5851 
create(ReporterConfig const & config) const5852             IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5853                 return std::unique_ptr<T>( new T( config ) );
5854             }
5855 
getDescription() const5856             std::string getDescription() const override {
5857                 return T::getDescription();
5858             }
5859         };
5860 
5861     public:
5862 
ReporterRegistrar(std::string const & name)5863         explicit ReporterRegistrar( std::string const& name ) {
5864             getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
5865         }
5866     };
5867 
5868     template<typename T>
5869     class ListenerRegistrar {
5870 
5871         class ListenerFactory : public IReporterFactory {
5872 
create(ReporterConfig const & config) const5873             IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5874                 return std::unique_ptr<T>( new T( config ) );
5875             }
getDescription() const5876             std::string getDescription() const override {
5877                 return std::string();
5878             }
5879         };
5880 
5881     public:
5882 
ListenerRegistrar()5883         ListenerRegistrar() {
5884             getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
5885         }
5886     };
5887 }
5888 
5889 #if !defined(CATCH_CONFIG_DISABLE)
5890 
5891 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
5892     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS          \
5893     namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
5894     CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
5895 
5896 #define CATCH_REGISTER_LISTENER( listenerType ) \
5897      CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS   \
5898      namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
5899      CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
5900 #else // CATCH_CONFIG_DISABLE
5901 
5902 #define CATCH_REGISTER_REPORTER(name, reporterType)
5903 #define CATCH_REGISTER_LISTENER(listenerType)
5904 
5905 #endif // CATCH_CONFIG_DISABLE
5906 
5907 // end catch_reporter_registrars.hpp
5908 // Allow users to base their work off existing reporters
5909 // start catch_reporter_compact.h
5910 
5911 namespace Catch {
5912 
5913     struct CompactReporter : StreamingReporterBase<CompactReporter> {
5914 
5915         using StreamingReporterBase::StreamingReporterBase;
5916 
5917         ~CompactReporter() override;
5918 
5919         static std::string getDescription();
5920 
5921         ReporterPreferences getPreferences() const override;
5922 
5923         void noMatchingTestCases(std::string const& spec) override;
5924 
5925         void assertionStarting(AssertionInfo const&) override;
5926 
5927         bool assertionEnded(AssertionStats const& _assertionStats) override;
5928 
5929         void sectionEnded(SectionStats const& _sectionStats) override;
5930 
5931         void testRunEnded(TestRunStats const& _testRunStats) override;
5932 
5933     };
5934 
5935 } // end namespace Catch
5936 
5937 // end catch_reporter_compact.h
5938 // start catch_reporter_console.h
5939 
5940 #if defined(_MSC_VER)
5941 #pragma warning(push)
5942 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
5943                               // Note that 4062 (not all labels are handled
5944                               // and default is missing) is enabled
5945 #endif
5946 
5947 namespace Catch {
5948     // Fwd decls
5949     struct SummaryColumn;
5950     class TablePrinter;
5951 
5952     struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
5953         std::unique_ptr<TablePrinter> m_tablePrinter;
5954 
5955         ConsoleReporter(ReporterConfig const& config);
5956         ~ConsoleReporter() override;
5957         static std::string getDescription();
5958 
5959         void noMatchingTestCases(std::string const& spec) override;
5960 
5961         void assertionStarting(AssertionInfo const&) override;
5962 
5963         bool assertionEnded(AssertionStats const& _assertionStats) override;
5964 
5965         void sectionStarting(SectionInfo const& _sectionInfo) override;
5966         void sectionEnded(SectionStats const& _sectionStats) override;
5967 
5968 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5969         void benchmarkPreparing(std::string const& name) override;
5970         void benchmarkStarting(BenchmarkInfo const& info) override;
5971         void benchmarkEnded(BenchmarkStats<> const& stats) override;
5972         void benchmarkFailed(std::string const& error) override;
5973 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5974 
5975         void testCaseEnded(TestCaseStats const& _testCaseStats) override;
5976         void testGroupEnded(TestGroupStats const& _testGroupStats) override;
5977         void testRunEnded(TestRunStats const& _testRunStats) override;
5978         void testRunStarting(TestRunInfo const& _testRunInfo) override;
5979     private:
5980 
5981         void lazyPrint();
5982 
5983         void lazyPrintWithoutClosingBenchmarkTable();
5984         void lazyPrintRunInfo();
5985         void lazyPrintGroupInfo();
5986         void printTestCaseAndSectionHeader();
5987 
5988         void printClosedHeader(std::string const& _name);
5989         void printOpenHeader(std::string const& _name);
5990 
5991         // if string has a : in first line will set indent to follow it on
5992         // subsequent lines
5993         void printHeaderString(std::string const& _string, std::size_t indent = 0);
5994 
5995         void printTotals(Totals const& totals);
5996         void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
5997 
5998         void printTotalsDivider(Totals const& totals);
5999         void printSummaryDivider();
6000         void printTestFilters();
6001 
6002     private:
6003         bool m_headerPrinted = false;
6004     };
6005 
6006 } // end namespace Catch
6007 
6008 #if defined(_MSC_VER)
6009 #pragma warning(pop)
6010 #endif
6011 
6012 // end catch_reporter_console.h
6013 // start catch_reporter_junit.h
6014 
6015 // start catch_xmlwriter.h
6016 
6017 #include <vector>
6018 
6019 namespace Catch {
6020 
6021     class XmlEncode {
6022     public:
6023         enum ForWhat { ForTextNodes, ForAttributes };
6024 
6025         XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6026 
6027         void encodeTo( std::ostream& os ) const;
6028 
6029         friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6030 
6031     private:
6032         std::string m_str;
6033         ForWhat m_forWhat;
6034     };
6035 
6036     class XmlWriter {
6037     public:
6038 
6039         class ScopedElement {
6040         public:
6041             ScopedElement( XmlWriter* writer );
6042 
6043             ScopedElement( ScopedElement&& other ) noexcept;
6044             ScopedElement& operator=( ScopedElement&& other ) noexcept;
6045 
6046             ~ScopedElement();
6047 
6048             ScopedElement& writeText( std::string const& text, bool indent = true );
6049 
6050             template<typename T>
writeAttribute(std::string const & name,T const & attribute)6051             ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6052                 m_writer->writeAttribute( name, attribute );
6053                 return *this;
6054             }
6055 
6056         private:
6057             mutable XmlWriter* m_writer = nullptr;
6058         };
6059 
6060         XmlWriter( std::ostream& os = Catch::cout() );
6061         ~XmlWriter();
6062 
6063         XmlWriter( XmlWriter const& ) = delete;
6064         XmlWriter& operator=( XmlWriter const& ) = delete;
6065 
6066         XmlWriter& startElement( std::string const& name );
6067 
6068         ScopedElement scopedElement( std::string const& name );
6069 
6070         XmlWriter& endElement();
6071 
6072         XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6073 
6074         XmlWriter& writeAttribute( std::string const& name, bool attribute );
6075 
6076         template<typename T>
writeAttribute(std::string const & name,T const & attribute)6077         XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6078             ReusableStringStream rss;
6079             rss << attribute;
6080             return writeAttribute( name, rss.str() );
6081         }
6082 
6083         XmlWriter& writeText( std::string const& text, bool indent = true );
6084 
6085         XmlWriter& writeComment( std::string const& text );
6086 
6087         void writeStylesheetRef( std::string const& url );
6088 
6089         XmlWriter& writeBlankLine();
6090 
6091         void ensureTagClosed();
6092 
6093     private:
6094 
6095         void writeDeclaration();
6096 
6097         void newlineIfNecessary();
6098 
6099         bool m_tagIsOpen = false;
6100         bool m_needsNewline = false;
6101         std::vector<std::string> m_tags;
6102         std::string m_indent;
6103         std::ostream& m_os;
6104     };
6105 
6106 }
6107 
6108 // end catch_xmlwriter.h
6109 namespace Catch {
6110 
6111     class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6112     public:
6113         JunitReporter(ReporterConfig const& _config);
6114 
6115         ~JunitReporter() override;
6116 
6117         static std::string getDescription();
6118 
6119         void noMatchingTestCases(std::string const& /*spec*/) override;
6120 
6121         void testRunStarting(TestRunInfo const& runInfo) override;
6122 
6123         void testGroupStarting(GroupInfo const& groupInfo) override;
6124 
6125         void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6126         bool assertionEnded(AssertionStats const& assertionStats) override;
6127 
6128         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6129 
6130         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6131 
6132         void testRunEndedCumulative() override;
6133 
6134         void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6135 
6136         void writeTestCase(TestCaseNode const& testCaseNode);
6137 
6138         void writeSection(std::string const& className,
6139                           std::string const& rootName,
6140                           SectionNode const& sectionNode);
6141 
6142         void writeAssertions(SectionNode const& sectionNode);
6143         void writeAssertion(AssertionStats const& stats);
6144 
6145         XmlWriter xml;
6146         Timer suiteTimer;
6147         std::string stdOutForSuite;
6148         std::string stdErrForSuite;
6149         unsigned int unexpectedExceptions = 0;
6150         bool m_okToFail = false;
6151     };
6152 
6153 } // end namespace Catch
6154 
6155 // end catch_reporter_junit.h
6156 // start catch_reporter_xml.h
6157 
6158 namespace Catch {
6159     class XmlReporter : public StreamingReporterBase<XmlReporter> {
6160     public:
6161         XmlReporter(ReporterConfig const& _config);
6162 
6163         ~XmlReporter() override;
6164 
6165         static std::string getDescription();
6166 
6167         virtual std::string getStylesheetRef() const;
6168 
6169         void writeSourceInfo(SourceLineInfo const& sourceInfo);
6170 
6171     public: // StreamingReporterBase
6172 
6173         void noMatchingTestCases(std::string const& s) override;
6174 
6175         void testRunStarting(TestRunInfo const& testInfo) override;
6176 
6177         void testGroupStarting(GroupInfo const& groupInfo) override;
6178 
6179         void testCaseStarting(TestCaseInfo const& testInfo) override;
6180 
6181         void sectionStarting(SectionInfo const& sectionInfo) override;
6182 
6183         void assertionStarting(AssertionInfo const&) override;
6184 
6185         bool assertionEnded(AssertionStats const& assertionStats) override;
6186 
6187         void sectionEnded(SectionStats const& sectionStats) override;
6188 
6189         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6190 
6191         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6192 
6193         void testRunEnded(TestRunStats const& testRunStats) override;
6194 
6195 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6196         void benchmarkPreparing(std::string const& name) override;
6197         void benchmarkStarting(BenchmarkInfo const&) override;
6198         void benchmarkEnded(BenchmarkStats<> const&) override;
6199         void benchmarkFailed(std::string const&) override;
6200 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6201 
6202     private:
6203         Timer m_testCaseTimer;
6204         XmlWriter m_xml;
6205         int m_sectionDepth = 0;
6206     };
6207 
6208 } // end namespace Catch
6209 
6210 // end catch_reporter_xml.h
6211 
6212 // end catch_external_interfaces.h
6213 #endif
6214 
6215 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6216 // start catch_benchmark.hpp
6217 
6218  // Benchmark
6219 
6220 // start catch_chronometer.hpp
6221 
6222 // User-facing chronometer
6223 
6224 
6225 // start catch_clock.hpp
6226 
6227 // Clocks
6228 
6229 
6230 #include <chrono>
6231 #include <ratio>
6232 
6233 namespace Catch {
6234     namespace Benchmark {
6235         template <typename Clock>
6236         using ClockDuration = typename Clock::duration;
6237         template <typename Clock>
6238         using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6239 
6240         template <typename Clock>
6241         using TimePoint = typename Clock::time_point;
6242 
6243         using default_clock = std::chrono::steady_clock;
6244 
6245         template <typename Clock>
6246         struct now {
operator ()Catch::Benchmark::now6247             TimePoint<Clock> operator()() const {
6248                 return Clock::now();
6249             }
6250         };
6251 
6252         using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6253     } // namespace Benchmark
6254 } // namespace Catch
6255 
6256 // end catch_clock.hpp
6257 // start catch_optimizer.hpp
6258 
6259  // Hinting the optimizer
6260 
6261 
6262 #if defined(_MSC_VER)
6263 #   include <atomic> // atomic_thread_fence
6264 #endif
6265 
6266 namespace Catch {
6267     namespace Benchmark {
6268 #if defined(__GNUC__) || defined(__clang__)
6269         template <typename T>
keep_memory(T * p)6270         inline void keep_memory(T* p) {
6271             asm volatile("" : : "g"(p) : "memory");
6272         }
keep_memory()6273         inline void keep_memory() {
6274             asm volatile("" : : : "memory");
6275         }
6276 
6277         namespace Detail {
optimizer_barrier()6278             inline void optimizer_barrier() { keep_memory(); }
6279         } // namespace Detail
6280 #elif defined(_MSC_VER)
6281 
6282 #pragma optimize("", off)
6283         template <typename T>
6284         inline void keep_memory(T* p) {
6285             // thanks @milleniumbug
6286             *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6287         }
6288         // TODO equivalent keep_memory()
6289 #pragma optimize("", on)
6290 
6291         namespace Detail {
6292             inline void optimizer_barrier() {
6293                 std::atomic_thread_fence(std::memory_order_seq_cst);
6294             }
6295         } // namespace Detail
6296 
6297 #endif
6298 
6299         template <typename T>
deoptimize_value(T && x)6300         inline void deoptimize_value(T&& x) {
6301             keep_memory(&x);
6302         }
6303 
6304         template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6305         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6306             deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6307         }
6308 
6309         template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6310         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6311             std::forward<Fn>(fn) (std::forward<Args...>(args...));
6312         }
6313     } // namespace Benchmark
6314 } // namespace Catch
6315 
6316 // end catch_optimizer.hpp
6317 // start catch_complete_invoke.hpp
6318 
6319 // Invoke with a special case for void
6320 
6321 
6322 #include <type_traits>
6323 #include <utility>
6324 
6325 namespace Catch {
6326     namespace Benchmark {
6327         namespace Detail {
6328             template <typename T>
6329             struct CompleteType { using type = T; };
6330             template <>
6331             struct CompleteType<void> { struct type {}; };
6332 
6333             template <typename T>
6334             using CompleteType_t = typename CompleteType<T>::type;
6335 
6336             template <typename Result>
6337             struct CompleteInvoker {
6338                 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6339                 static Result invoke(Fun&& fun, Args&&... args) {
6340                     return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6341                 }
6342             };
6343             template <>
6344             struct CompleteInvoker<void> {
6345                 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6346                 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6347                     std::forward<Fun>(fun)(std::forward<Args>(args)...);
6348                     return {};
6349                 }
6350             };
6351             template <typename Sig>
6352             using ResultOf_t = typename std::result_of<Sig>::type;
6353 
6354             // invoke and not return void :(
6355             template <typename Fun, typename... Args>
complete_invoke(Fun && fun,Args &&...args)6356             CompleteType_t<ResultOf_t<Fun(Args...)>> complete_invoke(Fun&& fun, Args&&... args) {
6357                 return CompleteInvoker<ResultOf_t<Fun(Args...)>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6358             }
6359 
6360             const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6361         } // namespace Detail
6362 
6363         template <typename Fun>
user_code(Fun && fun)6364         Detail::CompleteType_t<Detail::ResultOf_t<Fun()>> user_code(Fun&& fun) {
6365             CATCH_TRY{
6366                 return Detail::complete_invoke(std::forward<Fun>(fun));
6367             } CATCH_CATCH_ALL{
6368                 getResultCapture().benchmarkFailed(translateActiveException());
6369                 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6370             }
6371         }
6372     } // namespace Benchmark
6373 } // namespace Catch
6374 
6375 // end catch_complete_invoke.hpp
6376 namespace Catch {
6377     namespace Benchmark {
6378         namespace Detail {
6379             struct ChronometerConcept {
6380                 virtual void start() = 0;
6381                 virtual void finish() = 0;
6382                 virtual ~ChronometerConcept() = default;
6383             };
6384             template <typename Clock>
6385             struct ChronometerModel final : public ChronometerConcept {
startCatch::Benchmark::Detail::ChronometerModel6386                 void start() override { started = Clock::now(); }
finishCatch::Benchmark::Detail::ChronometerModel6387                 void finish() override { finished = Clock::now(); }
6388 
elapsedCatch::Benchmark::Detail::ChronometerModel6389                 ClockDuration<Clock> elapsed() const { return finished - started; }
6390 
6391                 TimePoint<Clock> started;
6392                 TimePoint<Clock> finished;
6393             };
6394         } // namespace Detail
6395 
6396         struct Chronometer {
6397         public:
6398             template <typename Fun>
measureCatch::Benchmark::Chronometer6399             void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6400 
runsCatch::Benchmark::Chronometer6401             int runs() const { return k; }
6402 
ChronometerCatch::Benchmark::Chronometer6403             Chronometer(Detail::ChronometerConcept& meter, int k)
6404                 : impl(&meter)
6405                 , k(k) {}
6406 
6407         private:
6408             template <typename Fun>
measureCatch::Benchmark::Chronometer6409             void measure(Fun&& fun, std::false_type) {
6410                 measure([&fun](int) { return fun(); }, std::true_type());
6411             }
6412 
6413             template <typename Fun>
measureCatch::Benchmark::Chronometer6414             void measure(Fun&& fun, std::true_type) {
6415                 Detail::optimizer_barrier();
6416                 impl->start();
6417                 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6418                 impl->finish();
6419                 Detail::optimizer_barrier();
6420             }
6421 
6422             Detail::ChronometerConcept* impl;
6423             int k;
6424         };
6425     } // namespace Benchmark
6426 } // namespace Catch
6427 
6428 // end catch_chronometer.hpp
6429 // start catch_environment.hpp
6430 
6431 // Environment information
6432 
6433 
6434 namespace Catch {
6435     namespace Benchmark {
6436         template <typename Duration>
6437         struct EnvironmentEstimate {
6438             Duration mean;
6439             OutlierClassification outliers;
6440 
6441             template <typename Duration2>
operator EnvironmentEstimate<Duration2>Catch::Benchmark::EnvironmentEstimate6442             operator EnvironmentEstimate<Duration2>() const {
6443                 return { mean, outliers };
6444             }
6445         };
6446         template <typename Clock>
6447         struct Environment {
6448             using clock_type = Clock;
6449             EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6450             EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6451         };
6452     } // namespace Benchmark
6453 } // namespace Catch
6454 
6455 // end catch_environment.hpp
6456 // start catch_execution_plan.hpp
6457 
6458  // Execution plan
6459 
6460 
6461 // start catch_benchmark_function.hpp
6462 
6463  // Dumb std::function implementation for consistent call overhead
6464 
6465 
6466 #include <cassert>
6467 #include <type_traits>
6468 #include <utility>
6469 #include <memory>
6470 
6471 namespace Catch {
6472     namespace Benchmark {
6473         namespace Detail {
6474             template <typename T>
6475             using Decay = typename std::decay<T>::type;
6476             template <typename T, typename U>
6477             struct is_related
6478                 : std::is_same<Decay<T>, Decay<U>> {};
6479 
6480             /// We need to reinvent std::function because every piece of code that might add overhead
6481             /// in a measurement context needs to have consistent performance characteristics so that we
6482             /// can account for it in the measurement.
6483             /// Implementations of std::function with optimizations that aren't always applicable, like
6484             /// small buffer optimizations, are not uncommon.
6485             /// This is effectively an implementation of std::function without any such optimizations;
6486             /// it may be slow, but it is consistently slow.
6487             struct BenchmarkFunction {
6488             private:
6489                 struct callable {
6490                     virtual void call(Chronometer meter) const = 0;
6491                     virtual callable* clone() const = 0;
6492                     virtual ~callable() = default;
6493                 };
6494                 template <typename Fun>
6495                 struct model : public callable {
modelCatch::Benchmark::Detail::BenchmarkFunction::model6496                     model(Fun&& fun) : fun(std::move(fun)) {}
modelCatch::Benchmark::Detail::BenchmarkFunction::model6497                     model(Fun const& fun) : fun(fun) {}
6498 
cloneCatch::Benchmark::Detail::BenchmarkFunction::model6499                     model<Fun>* clone() const override { return new model<Fun>(*this); }
6500 
callCatch::Benchmark::Detail::BenchmarkFunction::model6501                     void call(Chronometer meter) const override {
6502                         call(meter, is_callable<Fun(Chronometer)>());
6503                     }
callCatch::Benchmark::Detail::BenchmarkFunction::model6504                     void call(Chronometer meter, std::true_type) const {
6505                         fun(meter);
6506                     }
callCatch::Benchmark::Detail::BenchmarkFunction::model6507                     void call(Chronometer meter, std::false_type) const {
6508                         meter.measure(fun);
6509                     }
6510 
6511                     Fun fun;
6512                 };
6513 
operator ()Catch::Benchmark::Detail::BenchmarkFunction::do_nothing6514                 struct do_nothing { void operator()() const {} };
6515 
6516                 template <typename T>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6517                 BenchmarkFunction(model<T>* c) : f(c) {}
6518 
6519             public:
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6520                 BenchmarkFunction()
6521                     : f(new model<do_nothing>{ {} }) {}
6522 
6523                 template <typename Fun,
6524                     typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6525                     BenchmarkFunction(Fun&& fun)
6526                     : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6527 
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6528                 BenchmarkFunction(BenchmarkFunction&& that)
6529                     : f(std::move(that.f)) {}
6530 
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6531                 BenchmarkFunction(BenchmarkFunction const& that)
6532                     : f(that.f->clone()) {}
6533 
operator =Catch::Benchmark::Detail::BenchmarkFunction6534                 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6535                     f = std::move(that.f);
6536                     return *this;
6537                 }
6538 
operator =Catch::Benchmark::Detail::BenchmarkFunction6539                 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6540                     f.reset(that.f->clone());
6541                     return *this;
6542                 }
6543 
operator ()Catch::Benchmark::Detail::BenchmarkFunction6544                 void operator()(Chronometer meter) const { f->call(meter); }
6545 
6546             private:
6547                 std::unique_ptr<callable> f;
6548             };
6549         } // namespace Detail
6550     } // namespace Benchmark
6551 } // namespace Catch
6552 
6553 // end catch_benchmark_function.hpp
6554 // start catch_repeat.hpp
6555 
6556 // repeat algorithm
6557 
6558 
6559 #include <type_traits>
6560 #include <utility>
6561 
6562 namespace Catch {
6563     namespace Benchmark {
6564         namespace Detail {
6565             template <typename Fun>
6566             struct repeater {
operator ()Catch::Benchmark::Detail::repeater6567                 void operator()(int k) const {
6568                     for (int i = 0; i < k; ++i) {
6569                         fun();
6570                     }
6571                 }
6572                 Fun fun;
6573             };
6574             template <typename Fun>
repeat(Fun && fun)6575             repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6576                 return { std::forward<Fun>(fun) };
6577             }
6578         } // namespace Detail
6579     } // namespace Benchmark
6580 } // namespace Catch
6581 
6582 // end catch_repeat.hpp
6583 // start catch_run_for_at_least.hpp
6584 
6585 // Run a function for a minimum amount of time
6586 
6587 
6588 // start catch_measure.hpp
6589 
6590 // Measure
6591 
6592 
6593 // start catch_timing.hpp
6594 
6595 // Timing
6596 
6597 
6598 #include <tuple>
6599 #include <type_traits>
6600 
6601 namespace Catch {
6602     namespace Benchmark {
6603         template <typename Duration, typename Result>
6604         struct Timing {
6605             Duration elapsed;
6606             Result result;
6607             int iterations;
6608         };
6609         template <typename Clock, typename Sig>
6610         using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<Detail::ResultOf_t<Sig>>>;
6611     } // namespace Benchmark
6612 } // namespace Catch
6613 
6614 // end catch_timing.hpp
6615 #include <utility>
6616 
6617 namespace Catch {
6618     namespace Benchmark {
6619         namespace Detail {
6620             template <typename Clock, typename Fun, typename... Args>
measure(Fun && fun,Args &&...args)6621             TimingOf<Clock, Fun(Args...)> measure(Fun&& fun, Args&&... args) {
6622                 auto start = Clock::now();
6623                 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6624                 auto end = Clock::now();
6625                 auto delta = end - start;
6626                 return { delta, std::forward<decltype(r)>(r), 1 };
6627             }
6628         } // namespace Detail
6629     } // namespace Benchmark
6630 } // namespace Catch
6631 
6632 // end catch_measure.hpp
6633 #include <utility>
6634 #include <type_traits>
6635 
6636 namespace Catch {
6637     namespace Benchmark {
6638         namespace Detail {
6639             template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::false_type)6640             TimingOf<Clock, Fun(int)> measure_one(Fun&& fun, int iters, std::false_type) {
6641                 return Detail::measure<Clock>(fun, iters);
6642             }
6643             template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::true_type)6644             TimingOf<Clock, Fun(Chronometer)> measure_one(Fun&& fun, int iters, std::true_type) {
6645                 Detail::ChronometerModel<Clock> meter;
6646                 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6647 
6648                 return { meter.elapsed(), std::move(result), iters };
6649             }
6650 
6651             template <typename Clock, typename Fun>
6652             using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6653 
6654             struct optimized_away_error : std::exception {
whatCatch::Benchmark::Detail::optimized_away_error6655                 const char* what() const noexcept override {
6656                     return "could not measure benchmark, maybe it was optimized away";
6657                 }
6658             };
6659 
6660             template <typename Clock, typename Fun>
run_for_at_least(ClockDuration<Clock> how_long,int seed,Fun && fun)6661             TimingOf<Clock, Fun(run_for_at_least_argument_t<Clock, Fun>)> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6662                 auto iters = seed;
6663                 while (iters < (1 << 30)) {
6664                     auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6665 
6666                     if (Timing.elapsed >= how_long) {
6667                         return { Timing.elapsed, std::move(Timing.result), iters };
6668                     }
6669                     iters *= 2;
6670                 }
6671                 throw optimized_away_error{};
6672             }
6673         } // namespace Detail
6674     } // namespace Benchmark
6675 } // namespace Catch
6676 
6677 // end catch_run_for_at_least.hpp
6678 #include <algorithm>
6679 
6680 namespace Catch {
6681     namespace Benchmark {
6682         template <typename Duration>
6683         struct ExecutionPlan {
6684             int iterations_per_sample;
6685             Duration estimated_duration;
6686             Detail::BenchmarkFunction benchmark;
6687             Duration warmup_time;
6688             int warmup_iterations;
6689 
6690             template <typename Duration2>
operator ExecutionPlan<Duration2>Catch::Benchmark::ExecutionPlan6691             operator ExecutionPlan<Duration2>() const {
6692                 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6693             }
6694 
6695             template <typename Clock>
runCatch::Benchmark::ExecutionPlan6696             std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6697                 // warmup a bit
6698                 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6699 
6700                 std::vector<FloatDuration<Clock>> times;
6701                 times.reserve(cfg.benchmarkSamples());
6702                 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6703                     Detail::ChronometerModel<Clock> model;
6704                     this->benchmark(Chronometer(model, iterations_per_sample));
6705                     auto sample_time = model.elapsed() - env.clock_cost.mean;
6706                     if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6707                     return sample_time / iterations_per_sample;
6708                 });
6709                 return times;
6710             }
6711         };
6712     } // namespace Benchmark
6713 } // namespace Catch
6714 
6715 // end catch_execution_plan.hpp
6716 // start catch_estimate_clock.hpp
6717 
6718  // Environment measurement
6719 
6720 
6721 // start catch_stats.hpp
6722 
6723 // Statistical analysis tools
6724 
6725 
6726 #include <algorithm>
6727 #include <functional>
6728 #include <vector>
6729 #include <numeric>
6730 #include <tuple>
6731 #include <cmath>
6732 #include <utility>
6733 #include <cstddef>
6734 
6735 namespace Catch {
6736     namespace Benchmark {
6737         namespace Detail {
6738             using sample = std::vector<double>;
6739 
6740             double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6741 
6742             template <typename Iterator>
classify_outliers(Iterator first,Iterator last)6743             OutlierClassification classify_outliers(Iterator first, Iterator last) {
6744                 std::vector<double> copy(first, last);
6745 
6746                 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6747                 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6748                 auto iqr = q3 - q1;
6749                 auto los = q1 - (iqr * 3.);
6750                 auto lom = q1 - (iqr * 1.5);
6751                 auto him = q3 + (iqr * 1.5);
6752                 auto his = q3 + (iqr * 3.);
6753 
6754                 OutlierClassification o;
6755                 for (; first != last; ++first) {
6756                     auto&& t = *first;
6757                     if (t < los) ++o.low_severe;
6758                     else if (t < lom) ++o.low_mild;
6759                     else if (t > his) ++o.high_severe;
6760                     else if (t > him) ++o.high_mild;
6761                     ++o.samples_seen;
6762                 }
6763                 return o;
6764             }
6765 
6766             template <typename Iterator>
mean(Iterator first,Iterator last)6767             double mean(Iterator first, Iterator last) {
6768                 auto count = last - first;
6769                 double sum = std::accumulate(first, last, 0.);
6770                 return sum / count;
6771             }
6772 
6773             template <typename URng, typename Iterator, typename Estimator>
resample(URng & rng,int resamples,Iterator first,Iterator last,Estimator & estimator)6774             sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
6775                 auto n = last - first;
6776                 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6777 
6778                 sample out;
6779                 out.reserve(resamples);
6780                 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6781                     std::vector<double> resampled;
6782                     resampled.reserve(n);
6783                     std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
6784                     return estimator(resampled.begin(), resampled.end());
6785                 });
6786                 std::sort(out.begin(), out.end());
6787                 return out;
6788             }
6789 
6790             template <typename Estimator, typename Iterator>
jackknife(Estimator && estimator,Iterator first,Iterator last)6791             sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
6792                 auto n = last - first;
6793                 auto second = std::next(first);
6794                 sample results;
6795                 results.reserve(n);
6796 
6797                 for (auto it = first; it != last; ++it) {
6798                     std::iter_swap(it, first);
6799                     results.push_back(estimator(second, last));
6800                 }
6801 
6802                 return results;
6803             }
6804 
normal_cdf(double x)6805             inline double normal_cdf(double x) {
6806                 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
6807             }
6808 
6809             double erfc_inv(double x);
6810 
6811             double normal_quantile(double p);
6812 
6813             template <typename Iterator, typename Estimator>
bootstrap(double confidence_level,Iterator first,Iterator last,sample const & resample,Estimator && estimator)6814             Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
6815                 auto n_samples = last - first;
6816 
6817                 double point = estimator(first, last);
6818                 // Degenerate case with a single sample
6819                 if (n_samples == 1) return { point, point, point, confidence_level };
6820 
6821                 sample jack = jackknife(estimator, first, last);
6822                 double jack_mean = mean(jack.begin(), jack.end());
6823                 double sum_squares, sum_cubes;
6824                 std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
6825                     auto d = jack_mean - x;
6826                     auto d2 = d * d;
6827                     auto d3 = d2 * d;
6828                     return { sqcb.first + d2, sqcb.second + d3 };
6829                 });
6830 
6831                 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
6832                 int n = static_cast<int>(resample.size());
6833                 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
6834                 // degenerate case with uniform samples
6835                 if (prob_n == 0) return { point, point, point, confidence_level };
6836 
6837                 double bias = normal_quantile(prob_n);
6838                 double z1 = normal_quantile((1. - confidence_level) / 2.);
6839 
6840                 auto cumn = [n](double x) -> int {
6841                     return std::lround(normal_cdf(x) * n); };
6842                 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
6843                 double b1 = bias + z1;
6844                 double b2 = bias - z1;
6845                 double a1 = a(b1);
6846                 double a2 = a(b2);
6847                 auto lo = std::max(cumn(a1), 0);
6848                 auto hi = std::min(cumn(a2), n - 1);
6849 
6850                 return { point, resample[lo], resample[hi], confidence_level };
6851             }
6852 
6853             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
6854 
6855             struct bootstrap_analysis {
6856                 Estimate<double> mean;
6857                 Estimate<double> standard_deviation;
6858                 double outlier_variance;
6859             };
6860 
6861             bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
6862         } // namespace Detail
6863     } // namespace Benchmark
6864 } // namespace Catch
6865 
6866 // end catch_stats.hpp
6867 #include <algorithm>
6868 #include <iterator>
6869 #include <tuple>
6870 #include <vector>
6871 #include <cmath>
6872 
6873 namespace Catch {
6874     namespace Benchmark {
6875         namespace Detail {
6876             template <typename Clock>
resolution(int k)6877             std::vector<double> resolution(int k) {
6878                 std::vector<TimePoint<Clock>> times;
6879                 times.reserve(k + 1);
6880                 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
6881 
6882                 std::vector<double> deltas;
6883                 deltas.reserve(k);
6884                 std::transform(std::next(times.begin()), times.end(), times.begin(),
6885                     std::back_inserter(deltas),
6886                     [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
6887 
6888                 return deltas;
6889             }
6890 
6891             const auto warmup_iterations = 10000;
6892             const auto warmup_time = std::chrono::milliseconds(100);
6893             const auto minimum_ticks = 1000;
6894             const auto warmup_seed = 10000;
6895             const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
6896             const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
6897             const auto clock_cost_estimation_tick_limit = 100000;
6898             const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
6899             const auto clock_cost_estimation_iterations = 10000;
6900 
6901             template <typename Clock>
warmup()6902             int warmup() {
6903                 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
6904                     .iterations;
6905             }
6906             template <typename Clock>
estimate_clock_resolution(int iterations)6907             EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
6908                 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
6909                     .result;
6910                 return {
6911                     FloatDuration<Clock>(mean(r.begin(), r.end())),
6912                     classify_outliers(r.begin(), r.end()),
6913                 };
6914             }
6915             template <typename Clock>
estimate_clock_cost(FloatDuration<Clock> resolution)6916             EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
6917                 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
6918                 auto time_clock = [](int k) {
6919                     return Detail::measure<Clock>([k] {
6920                         for (int i = 0; i < k; ++i) {
6921                             volatile auto ignored = Clock::now();
6922                             (void)ignored;
6923                         }
6924                     }).elapsed;
6925                 };
6926                 time_clock(1);
6927                 int iters = clock_cost_estimation_iterations;
6928                 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
6929                 std::vector<double> times;
6930                 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
6931                 times.reserve(nsamples);
6932                 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
6933                     return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
6934                 });
6935                 return {
6936                     FloatDuration<Clock>(mean(times.begin(), times.end())),
6937                     classify_outliers(times.begin(), times.end()),
6938                 };
6939             }
6940 
6941             template <typename Clock>
measure_environment()6942             Environment<FloatDuration<Clock>> measure_environment() {
6943                 static Environment<FloatDuration<Clock>>* env = nullptr;
6944                 if (env) {
6945                     return *env;
6946                 }
6947 
6948                 auto iters = Detail::warmup<Clock>();
6949                 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
6950                 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
6951 
6952                 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
6953                 return *env;
6954             }
6955         } // namespace Detail
6956     } // namespace Benchmark
6957 } // namespace Catch
6958 
6959 // end catch_estimate_clock.hpp
6960 // start catch_analyse.hpp
6961 
6962  // Run and analyse one benchmark
6963 
6964 
6965 // start catch_sample_analysis.hpp
6966 
6967 // Benchmark results
6968 
6969 
6970 #include <algorithm>
6971 #include <vector>
6972 #include <string>
6973 #include <iterator>
6974 
6975 namespace Catch {
6976     namespace Benchmark {
6977         template <typename Duration>
6978         struct SampleAnalysis {
6979             std::vector<Duration> samples;
6980             Estimate<Duration> mean;
6981             Estimate<Duration> standard_deviation;
6982             OutlierClassification outliers;
6983             double outlier_variance;
6984 
6985             template <typename Duration2>
operator SampleAnalysis<Duration2>Catch::Benchmark::SampleAnalysis6986             operator SampleAnalysis<Duration2>() const {
6987                 std::vector<Duration2> samples2;
6988                 samples2.reserve(samples.size());
6989                 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
6990                 return {
6991                     std::move(samples2),
6992                     mean,
6993                     standard_deviation,
6994                     outliers,
6995                     outlier_variance,
6996                 };
6997             }
6998         };
6999     } // namespace Benchmark
7000 } // namespace Catch
7001 
7002 // end catch_sample_analysis.hpp
7003 #include <algorithm>
7004 #include <iterator>
7005 #include <vector>
7006 
7007 namespace Catch {
7008     namespace Benchmark {
7009         namespace Detail {
7010             template <typename Duration, typename Iterator>
analyse(const IConfig & cfg,Environment<Duration>,Iterator first,Iterator last)7011             SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7012                 if (!cfg.benchmarkNoAnalysis()) {
7013                     std::vector<double> samples;
7014                     samples.reserve(last - first);
7015                     std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7016 
7017                     auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7018                     auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7019 
7020                     auto wrap_estimate = [](Estimate<double> e) {
7021                         return Estimate<Duration> {
7022                             Duration(e.point),
7023                                 Duration(e.lower_bound),
7024                                 Duration(e.upper_bound),
7025                                 e.confidence_interval,
7026                         };
7027                     };
7028                     std::vector<Duration> samples2;
7029                     samples2.reserve(samples.size());
7030                     std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7031                     return {
7032                         std::move(samples2),
7033                         wrap_estimate(analysis.mean),
7034                         wrap_estimate(analysis.standard_deviation),
7035                         outliers,
7036                         analysis.outlier_variance,
7037                     };
7038                 } else {
7039                     std::vector<Duration> samples;
7040                     samples.reserve(last - first);
7041 
7042                     Duration mean = Duration(0);
7043                     int i = 0;
7044                     for (auto it = first; it < last; ++it, ++i) {
7045                         samples.push_back(Duration(*it));
7046                         mean += Duration(*it);
7047                     }
7048                     mean /= i;
7049 
7050                     return {
7051                         std::move(samples),
7052                         Estimate<Duration>{mean, mean, mean, 0.0},
7053                         Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7054                         OutlierClassification{},
7055                         0.0
7056                     };
7057                 }
7058             }
7059         } // namespace Detail
7060     } // namespace Benchmark
7061 } // namespace Catch
7062 
7063 // end catch_analyse.hpp
7064 #include <algorithm>
7065 #include <functional>
7066 #include <string>
7067 #include <vector>
7068 #include <cmath>
7069 
7070 namespace Catch {
7071     namespace Benchmark {
7072         struct Benchmark {
BenchmarkCatch::Benchmark::Benchmark7073             Benchmark(std::string &&name)
7074                 : name(std::move(name)) {}
7075 
7076             template <class FUN>
BenchmarkCatch::Benchmark::Benchmark7077             Benchmark(std::string &&name, FUN &&func)
7078                 : fun(std::move(func)), name(std::move(name)) {}
7079 
7080             template <typename Clock>
prepareCatch::Benchmark::Benchmark7081             ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7082                 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7083                 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(Detail::warmup_time));
7084                 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7085                 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7086                 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(Detail::warmup_time), Detail::warmup_iterations };
7087             }
7088 
7089             template <typename Clock = default_clock>
runCatch::Benchmark::Benchmark7090             void run() {
7091                 IConfigPtr cfg = getCurrentContext().getConfig();
7092 
7093                 auto env = Detail::measure_environment<Clock>();
7094 
7095                 getResultCapture().benchmarkPreparing(name);
7096                 CATCH_TRY{
7097                     auto plan = user_code([&] {
7098                         return prepare<Clock>(*cfg, env);
7099                     });
7100 
7101                     BenchmarkInfo info {
7102                         name,
7103                         plan.estimated_duration.count(),
7104                         plan.iterations_per_sample,
7105                         cfg->benchmarkSamples(),
7106                         cfg->benchmarkResamples(),
7107                         env.clock_resolution.mean.count(),
7108                         env.clock_cost.mean.count()
7109                     };
7110 
7111                     getResultCapture().benchmarkStarting(info);
7112 
7113                     auto samples = user_code([&] {
7114                         return plan.template run<Clock>(*cfg, env);
7115                     });
7116 
7117                     auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7118                     BenchmarkStats<std::chrono::duration<double, std::nano>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7119                     getResultCapture().benchmarkEnded(stats);
7120 
7121                 } CATCH_CATCH_ALL{
7122                     if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7123                         std::rethrow_exception(std::current_exception());
7124                 }
7125             }
7126 
7127             // sets lambda to be used in fun *and* executes benchmark!
7128             template <typename Fun,
7129                 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
operator =Catch::Benchmark::Benchmark7130                 Benchmark & operator=(Fun func) {
7131                 fun = Detail::BenchmarkFunction(func);
7132                 run();
7133                 return *this;
7134             }
7135 
operator boolCatch::Benchmark::Benchmark7136             explicit operator bool() {
7137                 return true;
7138             }
7139 
7140         private:
7141             Detail::BenchmarkFunction fun;
7142             std::string name;
7143         };
7144     }
7145 } // namespace Catch
7146 
7147 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7148 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7149 
7150 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7151     if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7152         BenchmarkName = [&](int benchmarkIndex)
7153 
7154 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7155     if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7156         BenchmarkName = [&]
7157 
7158 // end catch_benchmark.hpp
7159 #endif
7160 
7161 #endif // ! CATCH_CONFIG_IMPL_ONLY
7162 
7163 #ifdef CATCH_IMPL
7164 // start catch_impl.hpp
7165 
7166 #ifdef __clang__
7167 #pragma clang diagnostic push
7168 #pragma clang diagnostic ignored "-Wweak-vtables"
7169 #endif
7170 
7171 // Keep these here for external reporters
7172 // start catch_test_case_tracker.h
7173 
7174 #include <string>
7175 #include <vector>
7176 #include <memory>
7177 
7178 namespace Catch {
7179 namespace TestCaseTracking {
7180 
7181     struct NameAndLocation {
7182         std::string name;
7183         SourceLineInfo location;
7184 
7185         NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
7186     };
7187 
7188     struct ITracker;
7189 
7190     using ITrackerPtr = std::shared_ptr<ITracker>;
7191 
7192     struct ITracker {
7193         virtual ~ITracker();
7194 
7195         // static queries
7196         virtual NameAndLocation const& nameAndLocation() const = 0;
7197 
7198         // dynamic queries
7199         virtual bool isComplete() const = 0; // Successfully completed or failed
7200         virtual bool isSuccessfullyCompleted() const = 0;
7201         virtual bool isOpen() const = 0; // Started but not complete
7202         virtual bool hasChildren() const = 0;
7203 
7204         virtual ITracker& parent() = 0;
7205 
7206         // actions
7207         virtual void close() = 0; // Successfully complete
7208         virtual void fail() = 0;
7209         virtual void markAsNeedingAnotherRun() = 0;
7210 
7211         virtual void addChild( ITrackerPtr const& child ) = 0;
7212         virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7213         virtual void openChild() = 0;
7214 
7215         // Debug/ checking
7216         virtual bool isSectionTracker() const = 0;
7217         virtual bool isGeneratorTracker() const = 0;
7218     };
7219 
7220     class TrackerContext {
7221 
7222         enum RunState {
7223             NotStarted,
7224             Executing,
7225             CompletedCycle
7226         };
7227 
7228         ITrackerPtr m_rootTracker;
7229         ITracker* m_currentTracker = nullptr;
7230         RunState m_runState = NotStarted;
7231 
7232     public:
7233 
7234         ITracker& startRun();
7235         void endRun();
7236 
7237         void startCycle();
7238         void completeCycle();
7239 
7240         bool completedCycle() const;
7241         ITracker& currentTracker();
7242         void setCurrentTracker( ITracker* tracker );
7243     };
7244 
7245     class TrackerBase : public ITracker {
7246     protected:
7247         enum CycleState {
7248             NotStarted,
7249             Executing,
7250             ExecutingChildren,
7251             NeedsAnotherRun,
7252             CompletedSuccessfully,
7253             Failed
7254         };
7255 
7256         using Children = std::vector<ITrackerPtr>;
7257         NameAndLocation m_nameAndLocation;
7258         TrackerContext& m_ctx;
7259         ITracker* m_parent;
7260         Children m_children;
7261         CycleState m_runState = NotStarted;
7262 
7263     public:
7264         TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7265 
7266         NameAndLocation const& nameAndLocation() const override;
7267         bool isComplete() const override;
7268         bool isSuccessfullyCompleted() const override;
7269         bool isOpen() const override;
7270         bool hasChildren() const override;
7271 
7272         void addChild( ITrackerPtr const& child ) override;
7273 
7274         ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7275         ITracker& parent() override;
7276 
7277         void openChild() override;
7278 
7279         bool isSectionTracker() const override;
7280         bool isGeneratorTracker() const override;
7281 
7282         void open();
7283 
7284         void close() override;
7285         void fail() override;
7286         void markAsNeedingAnotherRun() override;
7287 
7288     private:
7289         void moveToParent();
7290         void moveToThis();
7291     };
7292 
7293     class SectionTracker : public TrackerBase {
7294         std::vector<std::string> m_filters;
7295     public:
7296         SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7297 
7298         bool isSectionTracker() const override;
7299 
7300         bool isComplete() const override;
7301 
7302         static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7303 
7304         void tryOpen();
7305 
7306         void addInitialFilters( std::vector<std::string> const& filters );
7307         void addNextFilters( std::vector<std::string> const& filters );
7308     };
7309 
7310 } // namespace TestCaseTracking
7311 
7312 using TestCaseTracking::ITracker;
7313 using TestCaseTracking::TrackerContext;
7314 using TestCaseTracking::SectionTracker;
7315 
7316 } // namespace Catch
7317 
7318 // end catch_test_case_tracker.h
7319 
7320 // start catch_leak_detector.h
7321 
7322 namespace Catch {
7323 
7324     struct LeakDetector {
7325         LeakDetector();
7326         ~LeakDetector();
7327     };
7328 
7329 }
7330 // end catch_leak_detector.h
7331 // Cpp files will be included in the single-header file here
7332 // start catch_stats.cpp
7333 
7334 // Statistical analysis tools
7335 
7336 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7337 
7338 #include <cassert>
7339 #include <random>
7340 
7341 #if defined(CATCH_CONFIG_USE_ASYNC)
7342 #include <future>
7343 #endif
7344 
7345 namespace {
erf_inv(double x)7346     double erf_inv(double x) {
7347         // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7348         double w, p;
7349 
7350         w = -log((1.0 - x) * (1.0 + x));
7351 
7352         if (w < 6.250000) {
7353             w = w - 3.125000;
7354             p = -3.6444120640178196996e-21;
7355             p = -1.685059138182016589e-19 + p * w;
7356             p = 1.2858480715256400167e-18 + p * w;
7357             p = 1.115787767802518096e-17 + p * w;
7358             p = -1.333171662854620906e-16 + p * w;
7359             p = 2.0972767875968561637e-17 + p * w;
7360             p = 6.6376381343583238325e-15 + p * w;
7361             p = -4.0545662729752068639e-14 + p * w;
7362             p = -8.1519341976054721522e-14 + p * w;
7363             p = 2.6335093153082322977e-12 + p * w;
7364             p = -1.2975133253453532498e-11 + p * w;
7365             p = -5.4154120542946279317e-11 + p * w;
7366             p = 1.051212273321532285e-09 + p * w;
7367             p = -4.1126339803469836976e-09 + p * w;
7368             p = -2.9070369957882005086e-08 + p * w;
7369             p = 4.2347877827932403518e-07 + p * w;
7370             p = -1.3654692000834678645e-06 + p * w;
7371             p = -1.3882523362786468719e-05 + p * w;
7372             p = 0.0001867342080340571352 + p * w;
7373             p = -0.00074070253416626697512 + p * w;
7374             p = -0.0060336708714301490533 + p * w;
7375             p = 0.24015818242558961693 + p * w;
7376             p = 1.6536545626831027356 + p * w;
7377         } else if (w < 16.000000) {
7378             w = sqrt(w) - 3.250000;
7379             p = 2.2137376921775787049e-09;
7380             p = 9.0756561938885390979e-08 + p * w;
7381             p = -2.7517406297064545428e-07 + p * w;
7382             p = 1.8239629214389227755e-08 + p * w;
7383             p = 1.5027403968909827627e-06 + p * w;
7384             p = -4.013867526981545969e-06 + p * w;
7385             p = 2.9234449089955446044e-06 + p * w;
7386             p = 1.2475304481671778723e-05 + p * w;
7387             p = -4.7318229009055733981e-05 + p * w;
7388             p = 6.8284851459573175448e-05 + p * w;
7389             p = 2.4031110387097893999e-05 + p * w;
7390             p = -0.0003550375203628474796 + p * w;
7391             p = 0.00095328937973738049703 + p * w;
7392             p = -0.0016882755560235047313 + p * w;
7393             p = 0.0024914420961078508066 + p * w;
7394             p = -0.0037512085075692412107 + p * w;
7395             p = 0.005370914553590063617 + p * w;
7396             p = 1.0052589676941592334 + p * w;
7397             p = 3.0838856104922207635 + p * w;
7398         } else {
7399             w = sqrt(w) - 5.000000;
7400             p = -2.7109920616438573243e-11;
7401             p = -2.5556418169965252055e-10 + p * w;
7402             p = 1.5076572693500548083e-09 + p * w;
7403             p = -3.7894654401267369937e-09 + p * w;
7404             p = 7.6157012080783393804e-09 + p * w;
7405             p = -1.4960026627149240478e-08 + p * w;
7406             p = 2.9147953450901080826e-08 + p * w;
7407             p = -6.7711997758452339498e-08 + p * w;
7408             p = 2.2900482228026654717e-07 + p * w;
7409             p = -9.9298272942317002539e-07 + p * w;
7410             p = 4.5260625972231537039e-06 + p * w;
7411             p = -1.9681778105531670567e-05 + p * w;
7412             p = 7.5995277030017761139e-05 + p * w;
7413             p = -0.00021503011930044477347 + p * w;
7414             p = -0.00013871931833623122026 + p * w;
7415             p = 1.0103004648645343977 + p * w;
7416             p = 4.8499064014085844221 + p * w;
7417         }
7418         return p * x;
7419     }
7420 
standard_deviation(std::vector<double>::iterator first,std::vector<double>::iterator last)7421     double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7422         auto m = Catch::Benchmark::Detail::mean(first, last);
7423         double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7424             double diff = b - m;
7425             return a + diff * diff;
7426             }) / (last - first);
7427             return std::sqrt(variance);
7428     }
7429 
7430 }
7431 
7432 namespace Catch {
7433     namespace Benchmark {
7434         namespace Detail {
7435 
weighted_average_quantile(int k,int q,std::vector<double>::iterator first,std::vector<double>::iterator last)7436             double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7437                 auto count = last - first;
7438                 double idx = (count - 1) * k / static_cast<double>(q);
7439                 int j = static_cast<int>(idx);
7440                 double g = idx - j;
7441                 std::nth_element(first, first + j, last);
7442                 auto xj = first[j];
7443                 if (g == 0) return xj;
7444 
7445                 auto xj1 = *std::min_element(first + (j + 1), last);
7446                 return xj + g * (xj1 - xj);
7447             }
7448 
erfc_inv(double x)7449             double erfc_inv(double x) {
7450                 return erf_inv(1.0 - x);
7451             }
7452 
normal_quantile(double p)7453             double normal_quantile(double p) {
7454                 static const double ROOT_TWO = std::sqrt(2.0);
7455 
7456                 double result = 0.0;
7457                 assert(p >= 0 && p <= 1);
7458                 if (p < 0 || p > 1) {
7459                     return result;
7460                 }
7461 
7462                 result = -erfc_inv(2.0 * p);
7463                 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7464                 result *= /*sd * */ ROOT_TWO;
7465                 // result += normal disttribution mean (0)
7466                 return result;
7467             }
7468 
outlier_variance(Estimate<double> mean,Estimate<double> stddev,int n)7469             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7470                 double sb = stddev.point;
7471                 double mn = mean.point / n;
7472                 double mg_min = mn / 2.;
7473                 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
7474                 double sg2 = sg * sg;
7475                 double sb2 = sb * sb;
7476 
7477                 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7478                     double k = mn - x;
7479                     double d = k * k;
7480                     double nd = n * d;
7481                     double k0 = -n * nd;
7482                     double k1 = sb2 - n * sg2 + nd;
7483                     double det = k1 * k1 - 4 * sg2 * k0;
7484                     return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7485                 };
7486 
7487                 auto var_out = [n, sb2, sg2](double c) {
7488                     double nc = n - c;
7489                     return (nc / n) * (sb2 - nc * sg2);
7490                 };
7491 
7492                 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
7493             }
7494 
analyse_samples(double confidence_level,int n_resamples,std::vector<double>::iterator first,std::vector<double>::iterator last)7495             bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7496                 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7497                 static std::random_device entropy;
7498                 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
7499 
7500                 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7501 
7502                 auto mean = &Detail::mean<std::vector<double>::iterator>;
7503                 auto stddev = &standard_deviation;
7504 
7505 #if defined(CATCH_CONFIG_USE_ASYNC)
7506                 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7507                     auto seed = entropy();
7508                     return std::async(std::launch::async, [=] {
7509                         std::mt19937 rng(seed);
7510                         auto resampled = resample(rng, n_resamples, first, last, f);
7511                         return bootstrap(confidence_level, first, last, resampled, f);
7512                     });
7513                 };
7514 
7515                 auto mean_future = Estimate(mean);
7516                 auto stddev_future = Estimate(stddev);
7517 
7518                 auto mean_estimate = mean_future.get();
7519                 auto stddev_estimate = stddev_future.get();
7520 #else
7521                 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7522                     auto seed = entropy();
7523                     std::mt19937 rng(seed);
7524                     auto resampled = resample(rng, n_resamples, first, last, f);
7525                     return bootstrap(confidence_level, first, last, resampled, f);
7526                 };
7527 
7528                 auto mean_estimate = Estimate(mean);
7529                 auto stddev_estimate = Estimate(stddev);
7530 #endif // CATCH_USE_ASYNC
7531 
7532                 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7533 
7534                 return { mean_estimate, stddev_estimate, outlier_variance };
7535             }
7536         } // namespace Detail
7537     } // namespace Benchmark
7538 } // namespace Catch
7539 
7540 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7541 // end catch_stats.cpp
7542 // start catch_approx.cpp
7543 
7544 #include <cmath>
7545 #include <limits>
7546 
7547 namespace {
7548 
7549 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7550 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)7551 bool marginComparison(double lhs, double rhs, double margin) {
7552     return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7553 }
7554 
7555 }
7556 
7557 namespace Catch {
7558 namespace Detail {
7559 
Approx(double value)7560     Approx::Approx ( double value )
7561     :   m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7562         m_margin( 0.0 ),
7563         m_scale( 0.0 ),
7564         m_value( value )
7565     {}
7566 
custom()7567     Approx Approx::custom() {
7568         return Approx( 0 );
7569     }
7570 
operator -() const7571     Approx Approx::operator-() const {
7572         auto temp(*this);
7573         temp.m_value = -temp.m_value;
7574         return temp;
7575     }
7576 
toString() const7577     std::string Approx::toString() const {
7578         ReusableStringStream rss;
7579         rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7580         return rss.str();
7581     }
7582 
equalityComparisonImpl(const double other) const7583     bool Approx::equalityComparisonImpl(const double other) const {
7584         // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7585         // Thanks to Richard Harris for his help refining the scaled margin value
7586         return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
7587     }
7588 
setMargin(double newMargin)7589     void Approx::setMargin(double newMargin) {
7590         CATCH_ENFORCE(newMargin >= 0,
7591             "Invalid Approx::margin: " << newMargin << '.'
7592             << " Approx::Margin has to be non-negative.");
7593         m_margin = newMargin;
7594     }
7595 
setEpsilon(double newEpsilon)7596     void Approx::setEpsilon(double newEpsilon) {
7597         CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7598             "Invalid Approx::epsilon: " << newEpsilon << '.'
7599             << " Approx::epsilon has to be in [0, 1]");
7600         m_epsilon = newEpsilon;
7601     }
7602 
7603 } // end namespace Detail
7604 
7605 namespace literals {
operator ""_a(long double val)7606     Detail::Approx operator "" _a(long double val) {
7607         return Detail::Approx(val);
7608     }
operator ""_a(unsigned long long val)7609     Detail::Approx operator "" _a(unsigned long long val) {
7610         return Detail::Approx(val);
7611     }
7612 } // end namespace literals
7613 
convert(Catch::Detail::Approx const & value)7614 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7615     return value.toString();
7616 }
7617 
7618 } // end namespace Catch
7619 // end catch_approx.cpp
7620 // start catch_assertionhandler.cpp
7621 
7622 // start catch_debugger.h
7623 
7624 namespace Catch {
7625     bool isDebuggerActive();
7626 }
7627 
7628 #ifdef CATCH_PLATFORM_MAC
7629 
7630     #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7631 
7632 #elif defined(CATCH_PLATFORM_LINUX)
7633     // If we can use inline assembler, do it because this allows us to break
7634     // directly at the location of the failing check instead of breaking inside
7635     // raise() called from it, i.e. one stack frame below.
7636     #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7637         #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7638     #else // Fall back to the generic way.
7639         #include <signal.h>
7640 
7641         #define CATCH_TRAP() raise(SIGTRAP)
7642     #endif
7643 #elif defined(_MSC_VER)
7644     #define CATCH_TRAP() __debugbreak()
7645 #elif defined(__MINGW32__)
7646     extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7647     #define CATCH_TRAP() DebugBreak()
7648 #endif
7649 
7650 #ifdef CATCH_TRAP
7651     #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7652 #else
7653     #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7654 #endif
7655 
7656 // end catch_debugger.h
7657 // start catch_run_context.h
7658 
7659 // start catch_fatal_condition.h
7660 
7661 // start catch_windows_h_proxy.h
7662 
7663 
7664 #if defined(CATCH_PLATFORM_WINDOWS)
7665 
7666 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
7667 #  define CATCH_DEFINED_NOMINMAX
7668 #  define NOMINMAX
7669 #endif
7670 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
7671 #  define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
7672 #  define WIN32_LEAN_AND_MEAN
7673 #endif
7674 
7675 #ifdef __AFXDLL
7676 #include <AfxWin.h>
7677 #else
7678 #include <windows.h>
7679 #endif
7680 
7681 #ifdef CATCH_DEFINED_NOMINMAX
7682 #  undef NOMINMAX
7683 #endif
7684 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
7685 #  undef WIN32_LEAN_AND_MEAN
7686 #endif
7687 
7688 #endif // defined(CATCH_PLATFORM_WINDOWS)
7689 
7690 // end catch_windows_h_proxy.h
7691 #if defined( CATCH_CONFIG_WINDOWS_SEH )
7692 
7693 namespace Catch {
7694 
7695     struct FatalConditionHandler {
7696 
7697         static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
7698         FatalConditionHandler();
7699         static void reset();
7700         ~FatalConditionHandler();
7701 
7702     private:
7703         static bool isSet;
7704         static ULONG guaranteeSize;
7705         static PVOID exceptionHandlerHandle;
7706     };
7707 
7708 } // namespace Catch
7709 
7710 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
7711 
7712 #include <signal.h>
7713 
7714 namespace Catch {
7715 
7716     struct FatalConditionHandler {
7717 
7718         static bool isSet;
7719         static struct sigaction oldSigActions[];
7720         static stack_t oldSigStack;
7721         static char altStackMem[];
7722 
7723         static void handleSignal( int sig );
7724 
7725         FatalConditionHandler();
7726         ~FatalConditionHandler();
7727         static void reset();
7728     };
7729 
7730 } // namespace Catch
7731 
7732 #else
7733 
7734 namespace Catch {
7735     struct FatalConditionHandler {
7736         void reset();
7737     };
7738 }
7739 
7740 #endif
7741 
7742 // end catch_fatal_condition.h
7743 #include <string>
7744 
7745 namespace Catch {
7746 
7747     struct IMutableContext;
7748 
7749     ///////////////////////////////////////////////////////////////////////////
7750 
7751     class RunContext : public IResultCapture, public IRunner {
7752 
7753     public:
7754         RunContext( RunContext const& ) = delete;
7755         RunContext& operator =( RunContext const& ) = delete;
7756 
7757         explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
7758 
7759         ~RunContext() override;
7760 
7761         void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
7762         void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
7763 
7764         Totals runTest(TestCase const& testCase);
7765 
7766         IConfigPtr config() const;
7767         IStreamingReporter& reporter() const;
7768 
7769     public: // IResultCapture
7770 
7771         // Assertion handlers
7772         void handleExpr
7773                 (   AssertionInfo const& info,
7774                     ITransientExpression const& expr,
7775                     AssertionReaction& reaction ) override;
7776         void handleMessage
7777                 (   AssertionInfo const& info,
7778                     ResultWas::OfType resultType,
7779                     StringRef const& message,
7780                     AssertionReaction& reaction ) override;
7781         void handleUnexpectedExceptionNotThrown
7782                 (   AssertionInfo const& info,
7783                     AssertionReaction& reaction ) override;
7784         void handleUnexpectedInflightException
7785                 (   AssertionInfo const& info,
7786                     std::string const& message,
7787                     AssertionReaction& reaction ) override;
7788         void handleIncomplete
7789                 (   AssertionInfo const& info ) override;
7790         void handleNonExpr
7791                 (   AssertionInfo const &info,
7792                     ResultWas::OfType resultType,
7793                     AssertionReaction &reaction ) override;
7794 
7795         bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
7796 
7797         void sectionEnded( SectionEndInfo const& endInfo ) override;
7798         void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
7799 
7800         auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
7801 
7802 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7803         void benchmarkPreparing( std::string const& name ) override;
7804         void benchmarkStarting( BenchmarkInfo const& info ) override;
7805         void benchmarkEnded( BenchmarkStats<> const& stats ) override;
7806         void benchmarkFailed( std::string const& error ) override;
7807 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7808 
7809         void pushScopedMessage( MessageInfo const& message ) override;
7810         void popScopedMessage( MessageInfo const& message ) override;
7811 
7812         void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
7813 
7814         std::string getCurrentTestName() const override;
7815 
7816         const AssertionResult* getLastResult() const override;
7817 
7818         void exceptionEarlyReported() override;
7819 
7820         void handleFatalErrorCondition( StringRef message ) override;
7821 
7822         bool lastAssertionPassed() override;
7823 
7824         void assertionPassed() override;
7825 
7826     public:
7827         // !TBD We need to do this another way!
7828         bool aborting() const final;
7829 
7830     private:
7831 
7832         void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
7833         void invokeActiveTestCase();
7834 
7835         void resetAssertionInfo();
7836         bool testForMissingAssertions( Counts& assertions );
7837 
7838         void assertionEnded( AssertionResult const& result );
7839         void reportExpr
7840                 (   AssertionInfo const &info,
7841                     ResultWas::OfType resultType,
7842                     ITransientExpression const *expr,
7843                     bool negated );
7844 
7845         void populateReaction( AssertionReaction& reaction );
7846 
7847     private:
7848 
7849         void handleUnfinishedSections();
7850 
7851         TestRunInfo m_runInfo;
7852         IMutableContext& m_context;
7853         TestCase const* m_activeTestCase = nullptr;
7854         ITracker* m_testCaseTracker = nullptr;
7855         Option<AssertionResult> m_lastResult;
7856 
7857         IConfigPtr m_config;
7858         Totals m_totals;
7859         IStreamingReporterPtr m_reporter;
7860         std::vector<MessageInfo> m_messages;
7861         std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
7862         AssertionInfo m_lastAssertionInfo;
7863         std::vector<SectionEndInfo> m_unfinishedSections;
7864         std::vector<ITracker*> m_activeSections;
7865         TrackerContext m_trackerContext;
7866         bool m_lastAssertionPassed = false;
7867         bool m_shouldReportUnexpected = true;
7868         bool m_includeSuccessfulResults;
7869     };
7870 
7871 } // end namespace Catch
7872 
7873 // end catch_run_context.h
7874 namespace Catch {
7875 
7876     namespace {
operator <<(std::ostream & os,ITransientExpression const & expr)7877         auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
7878             expr.streamReconstructedExpression( os );
7879             return os;
7880         }
7881     }
7882 
LazyExpression(bool isNegated)7883     LazyExpression::LazyExpression( bool isNegated )
7884     :   m_isNegated( isNegated )
7885     {}
7886 
LazyExpression(LazyExpression const & other)7887     LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
7888 
operator bool() const7889     LazyExpression::operator bool() const {
7890         return m_transientExpression != nullptr;
7891     }
7892 
operator <<(std::ostream & os,LazyExpression const & lazyExpr)7893     auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
7894         if( lazyExpr.m_isNegated )
7895             os << "!";
7896 
7897         if( lazyExpr ) {
7898             if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
7899                 os << "(" << *lazyExpr.m_transientExpression << ")";
7900             else
7901                 os << *lazyExpr.m_transientExpression;
7902         }
7903         else {
7904             os << "{** error - unchecked empty expression requested **}";
7905         }
7906         return os;
7907     }
7908 
AssertionHandler(StringRef const & macroName,SourceLineInfo const & lineInfo,StringRef capturedExpression,ResultDisposition::Flags resultDisposition)7909     AssertionHandler::AssertionHandler
7910         (   StringRef const& macroName,
7911             SourceLineInfo const& lineInfo,
7912             StringRef capturedExpression,
7913             ResultDisposition::Flags resultDisposition )
7914     :   m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
7915         m_resultCapture( getResultCapture() )
7916     {}
7917 
handleExpr(ITransientExpression const & expr)7918     void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
7919         m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
7920     }
handleMessage(ResultWas::OfType resultType,StringRef const & message)7921     void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
7922         m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
7923     }
7924 
allowThrows() const7925     auto AssertionHandler::allowThrows() const -> bool {
7926         return getCurrentContext().getConfig()->allowThrows();
7927     }
7928 
complete()7929     void AssertionHandler::complete() {
7930         setCompleted();
7931         if( m_reaction.shouldDebugBreak ) {
7932 
7933             // If you find your debugger stopping you here then go one level up on the
7934             // call-stack for the code that caused it (typically a failed assertion)
7935 
7936             // (To go back to the test and change execution, jump over the throw, next)
7937             CATCH_BREAK_INTO_DEBUGGER();
7938         }
7939         if (m_reaction.shouldThrow) {
7940 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
7941             throw Catch::TestFailureException();
7942 #else
7943             CATCH_ERROR( "Test failure requires aborting test!" );
7944 #endif
7945         }
7946     }
setCompleted()7947     void AssertionHandler::setCompleted() {
7948         m_completed = true;
7949     }
7950 
handleUnexpectedInflightException()7951     void AssertionHandler::handleUnexpectedInflightException() {
7952         m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
7953     }
7954 
handleExceptionThrownAsExpected()7955     void AssertionHandler::handleExceptionThrownAsExpected() {
7956         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7957     }
handleExceptionNotThrownAsExpected()7958     void AssertionHandler::handleExceptionNotThrownAsExpected() {
7959         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7960     }
7961 
handleUnexpectedExceptionNotThrown()7962     void AssertionHandler::handleUnexpectedExceptionNotThrown() {
7963         m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
7964     }
7965 
handleThrowingCallSkipped()7966     void AssertionHandler::handleThrowingCallSkipped() {
7967         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
7968     }
7969 
7970     // This is the overload that takes a string and infers the Equals matcher from it
7971     // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
handleExceptionMatchExpr(AssertionHandler & handler,std::string const & str,StringRef const & matcherString)7972     void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString  ) {
7973         handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
7974     }
7975 
7976 } // namespace Catch
7977 // end catch_assertionhandler.cpp
7978 // start catch_assertionresult.cpp
7979 
7980 namespace Catch {
AssertionResultData(ResultWas::OfType _resultType,LazyExpression const & _lazyExpression)7981     AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
7982         lazyExpression(_lazyExpression),
7983         resultType(_resultType) {}
7984 
reconstructExpression() const7985     std::string AssertionResultData::reconstructExpression() const {
7986 
7987         if( reconstructedExpression.empty() ) {
7988             if( lazyExpression ) {
7989                 ReusableStringStream rss;
7990                 rss << lazyExpression;
7991                 reconstructedExpression = rss.str();
7992             }
7993         }
7994         return reconstructedExpression;
7995     }
7996 
AssertionResult(AssertionInfo const & info,AssertionResultData const & data)7997     AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
7998     :   m_info( info ),
7999         m_resultData( data )
8000     {}
8001 
8002     // Result was a success
succeeded() const8003     bool AssertionResult::succeeded() const {
8004         return Catch::isOk( m_resultData.resultType );
8005     }
8006 
8007     // Result was a success, or failure is suppressed
isOk() const8008     bool AssertionResult::isOk() const {
8009         return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8010     }
8011 
getResultType() const8012     ResultWas::OfType AssertionResult::getResultType() const {
8013         return m_resultData.resultType;
8014     }
8015 
hasExpression() const8016     bool AssertionResult::hasExpression() const {
8017         return m_info.capturedExpression[0] != 0;
8018     }
8019 
hasMessage() const8020     bool AssertionResult::hasMessage() const {
8021         return !m_resultData.message.empty();
8022     }
8023 
getExpression() const8024     std::string AssertionResult::getExpression() const {
8025         if( isFalseTest( m_info.resultDisposition ) )
8026             return "!(" + m_info.capturedExpression + ")";
8027         else
8028             return m_info.capturedExpression;
8029     }
8030 
getExpressionInMacro() const8031     std::string AssertionResult::getExpressionInMacro() const {
8032         std::string expr;
8033         if( m_info.macroName[0] == 0 )
8034             expr = m_info.capturedExpression;
8035         else {
8036             expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8037             expr += m_info.macroName;
8038             expr += "( ";
8039             expr += m_info.capturedExpression;
8040             expr += " )";
8041         }
8042         return expr;
8043     }
8044 
hasExpandedExpression() const8045     bool AssertionResult::hasExpandedExpression() const {
8046         return hasExpression() && getExpandedExpression() != getExpression();
8047     }
8048 
getExpandedExpression() const8049     std::string AssertionResult::getExpandedExpression() const {
8050         std::string expr = m_resultData.reconstructExpression();
8051         return expr.empty()
8052                 ? getExpression()
8053                 : expr;
8054     }
8055 
getMessage() const8056     std::string AssertionResult::getMessage() const {
8057         return m_resultData.message;
8058     }
getSourceInfo() const8059     SourceLineInfo AssertionResult::getSourceInfo() const {
8060         return m_info.lineInfo;
8061     }
8062 
getTestMacroName() const8063     StringRef AssertionResult::getTestMacroName() const {
8064         return m_info.macroName;
8065     }
8066 
8067 } // end namespace Catch
8068 // end catch_assertionresult.cpp
8069 // start catch_capture_matchers.cpp
8070 
8071 namespace Catch {
8072 
8073     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8074 
8075     // This is the general overload that takes a any string matcher
8076     // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8077     // the Equals matcher (so the header does not mention matchers)
handleExceptionMatchExpr(AssertionHandler & handler,StringMatcher const & matcher,StringRef const & matcherString)8078     void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  ) {
8079         std::string exceptionMessage = Catch::translateActiveException();
8080         MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8081         handler.handleExpr( expr );
8082     }
8083 
8084 } // namespace Catch
8085 // end catch_capture_matchers.cpp
8086 // start catch_commandline.cpp
8087 
8088 // start catch_commandline.h
8089 
8090 // start catch_clara.h
8091 
8092 // Use Catch's value for console width (store Clara's off to the side, if present)
8093 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8094 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8095 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8096 #endif
8097 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8098 
8099 #ifdef __clang__
8100 #pragma clang diagnostic push
8101 #pragma clang diagnostic ignored "-Wweak-vtables"
8102 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8103 #pragma clang diagnostic ignored "-Wshadow"
8104 #endif
8105 
8106 // start clara.hpp
8107 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8108 //
8109 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8110 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8111 //
8112 // See https://github.com/philsquared/Clara for more details
8113 
8114 // Clara v1.1.5
8115 
8116 
8117 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8118 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8119 #endif
8120 
8121 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8122 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8123 #endif
8124 
8125 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8126 #ifdef __has_include
8127 #if __has_include(<optional>) && __cplusplus >= 201703L
8128 #include <optional>
8129 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8130 #endif
8131 #endif
8132 #endif
8133 
8134 // ----------- #included from clara_textflow.hpp -----------
8135 
8136 // TextFlowCpp
8137 //
8138 // A single-header library for wrapping and laying out basic text, by Phil Nash
8139 //
8140 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8141 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8142 //
8143 // This project is hosted at https://github.com/philsquared/textflowcpp
8144 
8145 
8146 #include <cassert>
8147 #include <ostream>
8148 #include <sstream>
8149 #include <vector>
8150 
8151 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8152 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8153 #endif
8154 
8155 namespace Catch {
8156 namespace clara {
8157 namespace TextFlow {
8158 
isWhitespace(char c)8159 inline auto isWhitespace(char c) -> bool {
8160 	static std::string chars = " \t\n\r";
8161 	return chars.find(c) != std::string::npos;
8162 }
isBreakableBefore(char c)8163 inline auto isBreakableBefore(char c) -> bool {
8164 	static std::string chars = "[({<|";
8165 	return chars.find(c) != std::string::npos;
8166 }
isBreakableAfter(char c)8167 inline auto isBreakableAfter(char c) -> bool {
8168 	static std::string chars = "])}>.,:;*+-=&/\\";
8169 	return chars.find(c) != std::string::npos;
8170 }
8171 
8172 class Columns;
8173 
8174 class Column {
8175 	std::vector<std::string> m_strings;
8176 	size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8177 	size_t m_indent = 0;
8178 	size_t m_initialIndent = std::string::npos;
8179 
8180 public:
8181 	class iterator {
8182 		friend Column;
8183 
8184 		Column const& m_column;
8185 		size_t m_stringIndex = 0;
8186 		size_t m_pos = 0;
8187 
8188 		size_t m_len = 0;
8189 		size_t m_end = 0;
8190 		bool m_suffix = false;
8191 
iterator(Column const & column,size_t stringIndex)8192 		iterator(Column const& column, size_t stringIndex)
8193 			: m_column(column),
8194 			m_stringIndex(stringIndex) {}
8195 
line() const8196 		auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8197 
isBoundary(size_t at) const8198 		auto isBoundary(size_t at) const -> bool {
8199 			assert(at > 0);
8200 			assert(at <= line().size());
8201 
8202 			return at == line().size() ||
8203 				(isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8204 				isBreakableBefore(line()[at]) ||
8205 				isBreakableAfter(line()[at - 1]);
8206 		}
8207 
calcLength()8208 		void calcLength() {
8209 			assert(m_stringIndex < m_column.m_strings.size());
8210 
8211 			m_suffix = false;
8212 			auto width = m_column.m_width - indent();
8213 			m_end = m_pos;
8214 			if (line()[m_pos] == '\n') {
8215 				++m_end;
8216 			}
8217 			while (m_end < line().size() && line()[m_end] != '\n')
8218 				++m_end;
8219 
8220 			if (m_end < m_pos + width) {
8221 				m_len = m_end - m_pos;
8222 			} else {
8223 				size_t len = width;
8224 				while (len > 0 && !isBoundary(m_pos + len))
8225 					--len;
8226 				while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8227 					--len;
8228 
8229 				if (len > 0) {
8230 					m_len = len;
8231 				} else {
8232 					m_suffix = true;
8233 					m_len = width - 1;
8234 				}
8235 			}
8236 		}
8237 
indent() const8238 		auto indent() const -> size_t {
8239 			auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8240 			return initial == std::string::npos ? m_column.m_indent : initial;
8241 		}
8242 
addIndentAndSuffix(std::string const & plain) const8243 		auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8244 			return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8245 		}
8246 
8247 	public:
8248 		using difference_type = std::ptrdiff_t;
8249 		using value_type = std::string;
8250 		using pointer = value_type * ;
8251 		using reference = value_type & ;
8252 		using iterator_category = std::forward_iterator_tag;
8253 
iterator(Column const & column)8254 		explicit iterator(Column const& column) : m_column(column) {
8255 			assert(m_column.m_width > m_column.m_indent);
8256 			assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8257 			calcLength();
8258 			if (m_len == 0)
8259 				m_stringIndex++; // Empty string
8260 		}
8261 
operator *() const8262 		auto operator *() const -> std::string {
8263 			assert(m_stringIndex < m_column.m_strings.size());
8264 			assert(m_pos <= m_end);
8265 			return addIndentAndSuffix(line().substr(m_pos, m_len));
8266 		}
8267 
operator ++()8268 		auto operator ++() -> iterator& {
8269 			m_pos += m_len;
8270 			if (m_pos < line().size() && line()[m_pos] == '\n')
8271 				m_pos += 1;
8272 			else
8273 				while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8274 					++m_pos;
8275 
8276 			if (m_pos == line().size()) {
8277 				m_pos = 0;
8278 				++m_stringIndex;
8279 			}
8280 			if (m_stringIndex < m_column.m_strings.size())
8281 				calcLength();
8282 			return *this;
8283 		}
operator ++(int)8284 		auto operator ++(int) -> iterator {
8285 			iterator prev(*this);
8286 			operator++();
8287 			return prev;
8288 		}
8289 
operator ==(iterator const & other) const8290 		auto operator ==(iterator const& other) const -> bool {
8291 			return
8292 				m_pos == other.m_pos &&
8293 				m_stringIndex == other.m_stringIndex &&
8294 				&m_column == &other.m_column;
8295 		}
operator !=(iterator const & other) const8296 		auto operator !=(iterator const& other) const -> bool {
8297 			return !operator==(other);
8298 		}
8299 	};
8300 	using const_iterator = iterator;
8301 
Column(std::string const & text)8302 	explicit Column(std::string const& text) { m_strings.push_back(text); }
8303 
width(size_t newWidth)8304 	auto width(size_t newWidth) -> Column& {
8305 		assert(newWidth > 0);
8306 		m_width = newWidth;
8307 		return *this;
8308 	}
indent(size_t newIndent)8309 	auto indent(size_t newIndent) -> Column& {
8310 		m_indent = newIndent;
8311 		return *this;
8312 	}
initialIndent(size_t newIndent)8313 	auto initialIndent(size_t newIndent) -> Column& {
8314 		m_initialIndent = newIndent;
8315 		return *this;
8316 	}
8317 
width() const8318 	auto width() const -> size_t { return m_width; }
begin() const8319 	auto begin() const -> iterator { return iterator(*this); }
end() const8320 	auto end() const -> iterator { return { *this, m_strings.size() }; }
8321 
operator <<(std::ostream & os,Column const & col)8322 	inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8323 		bool first = true;
8324 		for (auto line : col) {
8325 			if (first)
8326 				first = false;
8327 			else
8328 				os << "\n";
8329 			os << line;
8330 		}
8331 		return os;
8332 	}
8333 
8334 	auto operator + (Column const& other)->Columns;
8335 
toString() const8336 	auto toString() const -> std::string {
8337 		std::ostringstream oss;
8338 		oss << *this;
8339 		return oss.str();
8340 	}
8341 };
8342 
8343 class Spacer : public Column {
8344 
8345 public:
Spacer(size_t spaceWidth)8346 	explicit Spacer(size_t spaceWidth) : Column("") {
8347 		width(spaceWidth);
8348 	}
8349 };
8350 
8351 class Columns {
8352 	std::vector<Column> m_columns;
8353 
8354 public:
8355 
8356 	class iterator {
8357 		friend Columns;
8358 		struct EndTag {};
8359 
8360 		std::vector<Column> const& m_columns;
8361 		std::vector<Column::iterator> m_iterators;
8362 		size_t m_activeIterators;
8363 
iterator(Columns const & columns,EndTag)8364 		iterator(Columns const& columns, EndTag)
8365 			: m_columns(columns.m_columns),
8366 			m_activeIterators(0) {
8367 			m_iterators.reserve(m_columns.size());
8368 
8369 			for (auto const& col : m_columns)
8370 				m_iterators.push_back(col.end());
8371 		}
8372 
8373 	public:
8374 		using difference_type = std::ptrdiff_t;
8375 		using value_type = std::string;
8376 		using pointer = value_type * ;
8377 		using reference = value_type & ;
8378 		using iterator_category = std::forward_iterator_tag;
8379 
iterator(Columns const & columns)8380 		explicit iterator(Columns const& columns)
8381 			: m_columns(columns.m_columns),
8382 			m_activeIterators(m_columns.size()) {
8383 			m_iterators.reserve(m_columns.size());
8384 
8385 			for (auto const& col : m_columns)
8386 				m_iterators.push_back(col.begin());
8387 		}
8388 
operator ==(iterator const & other) const8389 		auto operator ==(iterator const& other) const -> bool {
8390 			return m_iterators == other.m_iterators;
8391 		}
operator !=(iterator const & other) const8392 		auto operator !=(iterator const& other) const -> bool {
8393 			return m_iterators != other.m_iterators;
8394 		}
operator *() const8395 		auto operator *() const -> std::string {
8396 			std::string row, padding;
8397 
8398 			for (size_t i = 0; i < m_columns.size(); ++i) {
8399 				auto width = m_columns[i].width();
8400 				if (m_iterators[i] != m_columns[i].end()) {
8401 					std::string col = *m_iterators[i];
8402 					row += padding + col;
8403 					if (col.size() < width)
8404 						padding = std::string(width - col.size(), ' ');
8405 					else
8406 						padding = "";
8407 				} else {
8408 					padding += std::string(width, ' ');
8409 				}
8410 			}
8411 			return row;
8412 		}
operator ++()8413 		auto operator ++() -> iterator& {
8414 			for (size_t i = 0; i < m_columns.size(); ++i) {
8415 				if (m_iterators[i] != m_columns[i].end())
8416 					++m_iterators[i];
8417 			}
8418 			return *this;
8419 		}
operator ++(int)8420 		auto operator ++(int) -> iterator {
8421 			iterator prev(*this);
8422 			operator++();
8423 			return prev;
8424 		}
8425 	};
8426 	using const_iterator = iterator;
8427 
begin() const8428 	auto begin() const -> iterator { return iterator(*this); }
end() const8429 	auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8430 
operator +=(Column const & col)8431 	auto operator += (Column const& col) -> Columns& {
8432 		m_columns.push_back(col);
8433 		return *this;
8434 	}
operator +(Column const & col)8435 	auto operator + (Column const& col) -> Columns {
8436 		Columns combined = *this;
8437 		combined += col;
8438 		return combined;
8439 	}
8440 
operator <<(std::ostream & os,Columns const & cols)8441 	inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8442 
8443 		bool first = true;
8444 		for (auto line : cols) {
8445 			if (first)
8446 				first = false;
8447 			else
8448 				os << "\n";
8449 			os << line;
8450 		}
8451 		return os;
8452 	}
8453 
toString() const8454 	auto toString() const -> std::string {
8455 		std::ostringstream oss;
8456 		oss << *this;
8457 		return oss.str();
8458 	}
8459 };
8460 
operator +(Column const & other)8461 inline auto Column::operator + (Column const& other) -> Columns {
8462 	Columns cols;
8463 	cols += *this;
8464 	cols += other;
8465 	return cols;
8466 }
8467 }
8468 
8469 }
8470 }
8471 
8472 // ----------- end of #include from clara_textflow.hpp -----------
8473 // ........... back in clara.hpp
8474 
8475 #include <cctype>
8476 #include <string>
8477 #include <memory>
8478 #include <set>
8479 #include <algorithm>
8480 
8481 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8482 #define CATCH_PLATFORM_WINDOWS
8483 #endif
8484 
8485 namespace Catch { namespace clara {
8486 namespace detail {
8487 
8488     // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8489     template<typename L>
8490     struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8491 
8492     template<typename ClassT, typename ReturnT, typename... Args>
8493     struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8494         static const bool isValid = false;
8495     };
8496 
8497     template<typename ClassT, typename ReturnT, typename ArgT>
8498     struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8499         static const bool isValid = true;
8500         using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8501         using ReturnType = ReturnT;
8502     };
8503 
8504     class TokenStream;
8505 
8506     // Transport for raw args (copied from main args, or supplied via init list for testing)
8507     class Args {
8508         friend TokenStream;
8509         std::string m_exeName;
8510         std::vector<std::string> m_args;
8511 
8512     public:
Args(int argc,char const * const * argv)8513         Args( int argc, char const* const* argv )
8514             : m_exeName(argv[0]),
8515               m_args(argv + 1, argv + argc) {}
8516 
Args(std::initializer_list<std::string> args)8517         Args( std::initializer_list<std::string> args )
8518         :   m_exeName( *args.begin() ),
8519             m_args( args.begin()+1, args.end() )
8520         {}
8521 
exeName() const8522         auto exeName() const -> std::string {
8523             return m_exeName;
8524         }
8525     };
8526 
8527     // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8528     // may encode an option + its argument if the : or = form is used
8529     enum class TokenType {
8530         Option, Argument
8531     };
8532     struct Token {
8533         TokenType type;
8534         std::string token;
8535     };
8536 
isOptPrefix(char c)8537     inline auto isOptPrefix( char c ) -> bool {
8538         return c == '-'
8539 #ifdef CATCH_PLATFORM_WINDOWS
8540             || c == '/'
8541 #endif
8542         ;
8543     }
8544 
8545     // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8546     class TokenStream {
8547         using Iterator = std::vector<std::string>::const_iterator;
8548         Iterator it;
8549         Iterator itEnd;
8550         std::vector<Token> m_tokenBuffer;
8551 
loadBuffer()8552         void loadBuffer() {
8553             m_tokenBuffer.resize( 0 );
8554 
8555             // Skip any empty strings
8556             while( it != itEnd && it->empty() )
8557                 ++it;
8558 
8559             if( it != itEnd ) {
8560                 auto const &next = *it;
8561                 if( isOptPrefix( next[0] ) ) {
8562                     auto delimiterPos = next.find_first_of( " :=" );
8563                     if( delimiterPos != std::string::npos ) {
8564                         m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8565                         m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8566                     } else {
8567                         if( next[1] != '-' && next.size() > 2 ) {
8568                             std::string opt = "- ";
8569                             for( size_t i = 1; i < next.size(); ++i ) {
8570                                 opt[1] = next[i];
8571                                 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8572                             }
8573                         } else {
8574                             m_tokenBuffer.push_back( { TokenType::Option, next } );
8575                         }
8576                     }
8577                 } else {
8578                     m_tokenBuffer.push_back( { TokenType::Argument, next } );
8579                 }
8580             }
8581         }
8582 
8583     public:
TokenStream(Args const & args)8584         explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8585 
TokenStream(Iterator it,Iterator itEnd)8586         TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8587             loadBuffer();
8588         }
8589 
operator bool() const8590         explicit operator bool() const {
8591             return !m_tokenBuffer.empty() || it != itEnd;
8592         }
8593 
count() const8594         auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8595 
operator *() const8596         auto operator*() const -> Token {
8597             assert( !m_tokenBuffer.empty() );
8598             return m_tokenBuffer.front();
8599         }
8600 
operator ->() const8601         auto operator->() const -> Token const * {
8602             assert( !m_tokenBuffer.empty() );
8603             return &m_tokenBuffer.front();
8604         }
8605 
operator ++()8606         auto operator++() -> TokenStream & {
8607             if( m_tokenBuffer.size() >= 2 ) {
8608                 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8609             } else {
8610                 if( it != itEnd )
8611                     ++it;
8612                 loadBuffer();
8613             }
8614             return *this;
8615         }
8616     };
8617 
8618     class ResultBase {
8619     public:
8620         enum Type {
8621             Ok, LogicError, RuntimeError
8622         };
8623 
8624     protected:
ResultBase(Type type)8625         ResultBase( Type type ) : m_type( type ) {}
8626         virtual ~ResultBase() = default;
8627 
8628         virtual void enforceOk() const = 0;
8629 
8630         Type m_type;
8631     };
8632 
8633     template<typename T>
8634     class ResultValueBase : public ResultBase {
8635     public:
value() const8636         auto value() const -> T const & {
8637             enforceOk();
8638             return m_value;
8639         }
8640 
8641     protected:
ResultValueBase(Type type)8642         ResultValueBase( Type type ) : ResultBase( type ) {}
8643 
ResultValueBase(ResultValueBase const & other)8644         ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8645             if( m_type == ResultBase::Ok )
8646                 new( &m_value ) T( other.m_value );
8647         }
8648 
ResultValueBase(Type,T const & value)8649         ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8650             new( &m_value ) T( value );
8651         }
8652 
operator =(ResultValueBase const & other)8653         auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8654             if( m_type == ResultBase::Ok )
8655                 m_value.~T();
8656             ResultBase::operator=(other);
8657             if( m_type == ResultBase::Ok )
8658                 new( &m_value ) T( other.m_value );
8659             return *this;
8660         }
8661 
~ResultValueBase()8662         ~ResultValueBase() override {
8663             if( m_type == Ok )
8664                 m_value.~T();
8665         }
8666 
8667         union {
8668             T m_value;
8669         };
8670     };
8671 
8672     template<>
8673     class ResultValueBase<void> : public ResultBase {
8674     protected:
8675         using ResultBase::ResultBase;
8676     };
8677 
8678     template<typename T = void>
8679     class BasicResult : public ResultValueBase<T> {
8680     public:
8681         template<typename U>
BasicResult(BasicResult<U> const & other)8682         explicit BasicResult( BasicResult<U> const &other )
8683         :   ResultValueBase<T>( other.type() ),
8684             m_errorMessage( other.errorMessage() )
8685         {
8686             assert( type() != ResultBase::Ok );
8687         }
8688 
8689         template<typename U>
ok(U const & value)8690         static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
ok()8691         static auto ok() -> BasicResult { return { ResultBase::Ok }; }
logicError(std::string const & message)8692         static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
runtimeError(std::string const & message)8693         static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
8694 
operator bool() const8695         explicit operator bool() const { return m_type == ResultBase::Ok; }
type() const8696         auto type() const -> ResultBase::Type { return m_type; }
errorMessage() const8697         auto errorMessage() const -> std::string { return m_errorMessage; }
8698 
8699     protected:
enforceOk() const8700         void enforceOk() const override {
8701 
8702             // Errors shouldn't reach this point, but if they do
8703             // the actual error message will be in m_errorMessage
8704             assert( m_type != ResultBase::LogicError );
8705             assert( m_type != ResultBase::RuntimeError );
8706             if( m_type != ResultBase::Ok )
8707                 std::abort();
8708         }
8709 
8710         std::string m_errorMessage; // Only populated if resultType is an error
8711 
BasicResult(ResultBase::Type type,std::string const & message)8712         BasicResult( ResultBase::Type type, std::string const &message )
8713         :   ResultValueBase<T>(type),
8714             m_errorMessage(message)
8715         {
8716             assert( m_type != ResultBase::Ok );
8717         }
8718 
8719         using ResultValueBase<T>::ResultValueBase;
8720         using ResultBase::m_type;
8721     };
8722 
8723     enum class ParseResultType {
8724         Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
8725     };
8726 
8727     class ParseState {
8728     public:
8729 
ParseState(ParseResultType type,TokenStream const & remainingTokens)8730         ParseState( ParseResultType type, TokenStream const &remainingTokens )
8731         : m_type(type),
8732           m_remainingTokens( remainingTokens )
8733         {}
8734 
type() const8735         auto type() const -> ParseResultType { return m_type; }
remainingTokens() const8736         auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
8737 
8738     private:
8739         ParseResultType m_type;
8740         TokenStream m_remainingTokens;
8741     };
8742 
8743     using Result = BasicResult<void>;
8744     using ParserResult = BasicResult<ParseResultType>;
8745     using InternalParseResult = BasicResult<ParseState>;
8746 
8747     struct HelpColumns {
8748         std::string left;
8749         std::string right;
8750     };
8751 
8752     template<typename T>
convertInto(std::string const & source,T & target)8753     inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
8754         std::stringstream ss;
8755         ss << source;
8756         ss >> target;
8757         if( ss.fail() )
8758             return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
8759         else
8760             return ParserResult::ok( ParseResultType::Matched );
8761     }
convertInto(std::string const & source,std::string & target)8762     inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
8763         target = source;
8764         return ParserResult::ok( ParseResultType::Matched );
8765     }
convertInto(std::string const & source,bool & target)8766     inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
8767         std::string srcLC = source;
8768         std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
8769         if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
8770             target = true;
8771         else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
8772             target = false;
8773         else
8774             return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
8775         return ParserResult::ok( ParseResultType::Matched );
8776     }
8777 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
8778     template<typename T>
convertInto(std::string const & source,CLARA_CONFIG_OPTIONAL_TYPE<T> & target)8779     inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
8780         T temp;
8781         auto result = convertInto( source, temp );
8782         if( result )
8783             target = std::move(temp);
8784         return result;
8785     }
8786 #endif // CLARA_CONFIG_OPTIONAL_TYPE
8787 
8788     struct NonCopyable {
8789         NonCopyable() = default;
8790         NonCopyable( NonCopyable const & ) = delete;
8791         NonCopyable( NonCopyable && ) = delete;
8792         NonCopyable &operator=( NonCopyable const & ) = delete;
8793         NonCopyable &operator=( NonCopyable && ) = delete;
8794     };
8795 
8796     struct BoundRef : NonCopyable {
8797         virtual ~BoundRef() = default;
isContainerCatch::clara::detail::BoundRef8798         virtual auto isContainer() const -> bool { return false; }
isFlagCatch::clara::detail::BoundRef8799         virtual auto isFlag() const -> bool { return false; }
8800     };
8801     struct BoundValueRefBase : BoundRef {
8802         virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
8803     };
8804     struct BoundFlagRefBase : BoundRef {
8805         virtual auto setFlag( bool flag ) -> ParserResult = 0;
isFlagCatch::clara::detail::BoundFlagRefBase8806         virtual auto isFlag() const -> bool { return true; }
8807     };
8808 
8809     template<typename T>
8810     struct BoundValueRef : BoundValueRefBase {
8811         T &m_ref;
8812 
BoundValueRefCatch::clara::detail::BoundValueRef8813         explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
8814 
setValueCatch::clara::detail::BoundValueRef8815         auto setValue( std::string const &arg ) -> ParserResult override {
8816             return convertInto( arg, m_ref );
8817         }
8818     };
8819 
8820     template<typename T>
8821     struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
8822         std::vector<T> &m_ref;
8823 
BoundValueRefCatch::clara::detail::BoundValueRef8824         explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
8825 
isContainerCatch::clara::detail::BoundValueRef8826         auto isContainer() const -> bool override { return true; }
8827 
setValueCatch::clara::detail::BoundValueRef8828         auto setValue( std::string const &arg ) -> ParserResult override {
8829             T temp;
8830             auto result = convertInto( arg, temp );
8831             if( result )
8832                 m_ref.push_back( temp );
8833             return result;
8834         }
8835     };
8836 
8837     struct BoundFlagRef : BoundFlagRefBase {
8838         bool &m_ref;
8839 
BoundFlagRefCatch::clara::detail::BoundFlagRef8840         explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
8841 
setFlagCatch::clara::detail::BoundFlagRef8842         auto setFlag( bool flag ) -> ParserResult override {
8843             m_ref = flag;
8844             return ParserResult::ok( ParseResultType::Matched );
8845         }
8846     };
8847 
8848     template<typename ReturnType>
8849     struct LambdaInvoker {
8850         static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
8851 
8852         template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker8853         static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
8854             return lambda( arg );
8855         }
8856     };
8857 
8858     template<>
8859     struct LambdaInvoker<void> {
8860         template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker8861         static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
8862             lambda( arg );
8863             return ParserResult::ok( ParseResultType::Matched );
8864         }
8865     };
8866 
8867     template<typename ArgType, typename L>
invokeLambda(L const & lambda,std::string const & arg)8868     inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
8869         ArgType temp{};
8870         auto result = convertInto( arg, temp );
8871         return !result
8872            ? result
8873            : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
8874     }
8875 
8876     template<typename L>
8877     struct BoundLambda : BoundValueRefBase {
8878         L m_lambda;
8879 
8880         static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
BoundLambdaCatch::clara::detail::BoundLambda8881         explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
8882 
setValueCatch::clara::detail::BoundLambda8883         auto setValue( std::string const &arg ) -> ParserResult override {
8884             return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
8885         }
8886     };
8887 
8888     template<typename L>
8889     struct BoundFlagLambda : BoundFlagRefBase {
8890         L m_lambda;
8891 
8892         static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
8893         static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
8894 
BoundFlagLambdaCatch::clara::detail::BoundFlagLambda8895         explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
8896 
setFlagCatch::clara::detail::BoundFlagLambda8897         auto setFlag( bool flag ) -> ParserResult override {
8898             return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
8899         }
8900     };
8901 
8902     enum class Optionality { Optional, Required };
8903 
8904     struct Parser;
8905 
8906     class ParserBase {
8907     public:
8908         virtual ~ParserBase() = default;
validate() const8909         virtual auto validate() const -> Result { return Result::ok(); }
8910         virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult  = 0;
cardinality() const8911         virtual auto cardinality() const -> size_t { return 1; }
8912 
parse(Args const & args) const8913         auto parse( Args const &args ) const -> InternalParseResult {
8914             return parse( args.exeName(), TokenStream( args ) );
8915         }
8916     };
8917 
8918     template<typename DerivedT>
8919     class ComposableParserImpl : public ParserBase {
8920     public:
8921         template<typename T>
8922         auto operator|( T const &other ) const -> Parser;
8923 
8924 		template<typename T>
8925         auto operator+( T const &other ) const -> Parser;
8926     };
8927 
8928     // Common code and state for Args and Opts
8929     template<typename DerivedT>
8930     class ParserRefImpl : public ComposableParserImpl<DerivedT> {
8931     protected:
8932         Optionality m_optionality = Optionality::Optional;
8933         std::shared_ptr<BoundRef> m_ref;
8934         std::string m_hint;
8935         std::string m_description;
8936 
ParserRefImpl(std::shared_ptr<BoundRef> const & ref)8937         explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
8938 
8939     public:
8940         template<typename T>
ParserRefImpl(T & ref,std::string const & hint)8941         ParserRefImpl( T &ref, std::string const &hint )
8942         :   m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
8943             m_hint( hint )
8944         {}
8945 
8946         template<typename LambdaT>
ParserRefImpl(LambdaT const & ref,std::string const & hint)8947         ParserRefImpl( LambdaT const &ref, std::string const &hint )
8948         :   m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
8949             m_hint(hint)
8950         {}
8951 
operator ()(std::string const & description)8952         auto operator()( std::string const &description ) -> DerivedT & {
8953             m_description = description;
8954             return static_cast<DerivedT &>( *this );
8955         }
8956 
optional()8957         auto optional() -> DerivedT & {
8958             m_optionality = Optionality::Optional;
8959             return static_cast<DerivedT &>( *this );
8960         };
8961 
required()8962         auto required() -> DerivedT & {
8963             m_optionality = Optionality::Required;
8964             return static_cast<DerivedT &>( *this );
8965         };
8966 
isOptional() const8967         auto isOptional() const -> bool {
8968             return m_optionality == Optionality::Optional;
8969         }
8970 
cardinality() const8971         auto cardinality() const -> size_t override {
8972             if( m_ref->isContainer() )
8973                 return 0;
8974             else
8975                 return 1;
8976         }
8977 
hint() const8978         auto hint() const -> std::string { return m_hint; }
8979     };
8980 
8981     class ExeName : public ComposableParserImpl<ExeName> {
8982         std::shared_ptr<std::string> m_name;
8983         std::shared_ptr<BoundValueRefBase> m_ref;
8984 
8985         template<typename LambdaT>
makeRef(LambdaT const & lambda)8986         static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
8987             return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
8988         }
8989 
8990     public:
ExeName()8991         ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
8992 
ExeName(std::string & ref)8993         explicit ExeName( std::string &ref ) : ExeName() {
8994             m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
8995         }
8996 
8997         template<typename LambdaT>
ExeName(LambdaT const & lambda)8998         explicit ExeName( LambdaT const& lambda ) : ExeName() {
8999             m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9000         }
9001 
9002         // The exe name is not parsed out of the normal tokens, but is handled specially
parse(std::string const &,TokenStream const & tokens) const9003         auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9004             return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9005         }
9006 
name() const9007         auto name() const -> std::string { return *m_name; }
set(std::string const & newName)9008         auto set( std::string const& newName ) -> ParserResult {
9009 
9010             auto lastSlash = newName.find_last_of( "\\/" );
9011             auto filename = ( lastSlash == std::string::npos )
9012                     ? newName
9013                     : newName.substr( lastSlash+1 );
9014 
9015             *m_name = filename;
9016             if( m_ref )
9017                 return m_ref->setValue( filename );
9018             else
9019                 return ParserResult::ok( ParseResultType::Matched );
9020         }
9021     };
9022 
9023     class Arg : public ParserRefImpl<Arg> {
9024     public:
9025         using ParserRefImpl::ParserRefImpl;
9026 
parse(std::string const &,TokenStream const & tokens) const9027         auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9028             auto validationResult = validate();
9029             if( !validationResult )
9030                 return InternalParseResult( validationResult );
9031 
9032             auto remainingTokens = tokens;
9033             auto const &token = *remainingTokens;
9034             if( token.type != TokenType::Argument )
9035                 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9036 
9037             assert( !m_ref->isFlag() );
9038             auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9039 
9040             auto result = valueRef->setValue( remainingTokens->token );
9041             if( !result )
9042                 return InternalParseResult( result );
9043             else
9044                 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9045         }
9046     };
9047 
normaliseOpt(std::string const & optName)9048     inline auto normaliseOpt( std::string const &optName ) -> std::string {
9049 #ifdef CATCH_PLATFORM_WINDOWS
9050         if( optName[0] == '/' )
9051             return "-" + optName.substr( 1 );
9052         else
9053 #endif
9054             return optName;
9055     }
9056 
9057     class Opt : public ParserRefImpl<Opt> {
9058     protected:
9059         std::vector<std::string> m_optNames;
9060 
9061     public:
9062         template<typename LambdaT>
Opt(LambdaT const & ref)9063         explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9064 
Opt(bool & ref)9065         explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9066 
9067         template<typename LambdaT>
Opt(LambdaT const & ref,std::string const & hint)9068         Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9069 
9070         template<typename T>
Opt(T & ref,std::string const & hint)9071         Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9072 
operator [](std::string const & optName)9073         auto operator[]( std::string const &optName ) -> Opt & {
9074             m_optNames.push_back( optName );
9075             return *this;
9076         }
9077 
getHelpColumns() const9078         auto getHelpColumns() const -> std::vector<HelpColumns> {
9079             std::ostringstream oss;
9080             bool first = true;
9081             for( auto const &opt : m_optNames ) {
9082                 if (first)
9083                     first = false;
9084                 else
9085                     oss << ", ";
9086                 oss << opt;
9087             }
9088             if( !m_hint.empty() )
9089                 oss << " <" << m_hint << ">";
9090             return { { oss.str(), m_description } };
9091         }
9092 
isMatch(std::string const & optToken) const9093         auto isMatch( std::string const &optToken ) const -> bool {
9094             auto normalisedToken = normaliseOpt( optToken );
9095             for( auto const &name : m_optNames ) {
9096                 if( normaliseOpt( name ) == normalisedToken )
9097                     return true;
9098             }
9099             return false;
9100         }
9101 
9102         using ParserBase::parse;
9103 
parse(std::string const &,TokenStream const & tokens) const9104         auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9105             auto validationResult = validate();
9106             if( !validationResult )
9107                 return InternalParseResult( validationResult );
9108 
9109             auto remainingTokens = tokens;
9110             if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9111                 auto const &token = *remainingTokens;
9112                 if( isMatch(token.token ) ) {
9113                     if( m_ref->isFlag() ) {
9114                         auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9115                         auto result = flagRef->setFlag( true );
9116                         if( !result )
9117                             return InternalParseResult( result );
9118                         if( result.value() == ParseResultType::ShortCircuitAll )
9119                             return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9120                     } else {
9121                         auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9122                         ++remainingTokens;
9123                         if( !remainingTokens )
9124                             return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9125                         auto const &argToken = *remainingTokens;
9126                         if( argToken.type != TokenType::Argument )
9127                             return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9128                         auto result = valueRef->setValue( argToken.token );
9129                         if( !result )
9130                             return InternalParseResult( result );
9131                         if( result.value() == ParseResultType::ShortCircuitAll )
9132                             return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9133                     }
9134                     return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9135                 }
9136             }
9137             return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9138         }
9139 
validate() const9140         auto validate() const -> Result override {
9141             if( m_optNames.empty() )
9142                 return Result::logicError( "No options supplied to Opt" );
9143             for( auto const &name : m_optNames ) {
9144                 if( name.empty() )
9145                     return Result::logicError( "Option name cannot be empty" );
9146 #ifdef CATCH_PLATFORM_WINDOWS
9147                 if( name[0] != '-' && name[0] != '/' )
9148                     return Result::logicError( "Option name must begin with '-' or '/'" );
9149 #else
9150                 if( name[0] != '-' )
9151                     return Result::logicError( "Option name must begin with '-'" );
9152 #endif
9153             }
9154             return ParserRefImpl::validate();
9155         }
9156     };
9157 
9158     struct Help : Opt {
HelpCatch::clara::detail::Help9159         Help( bool &showHelpFlag )
9160         :   Opt([&]( bool flag ) {
9161                 showHelpFlag = flag;
9162                 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9163             })
9164         {
9165             static_cast<Opt &>( *this )
9166                     ("display usage information")
9167                     ["-?"]["-h"]["--help"]
9168                     .optional();
9169         }
9170     };
9171 
9172     struct Parser : ParserBase {
9173 
9174         mutable ExeName m_exeName;
9175         std::vector<Opt> m_options;
9176         std::vector<Arg> m_args;
9177 
operator |=Catch::clara::detail::Parser9178         auto operator|=( ExeName const &exeName ) -> Parser & {
9179             m_exeName = exeName;
9180             return *this;
9181         }
9182 
operator |=Catch::clara::detail::Parser9183         auto operator|=( Arg const &arg ) -> Parser & {
9184             m_args.push_back(arg);
9185             return *this;
9186         }
9187 
operator |=Catch::clara::detail::Parser9188         auto operator|=( Opt const &opt ) -> Parser & {
9189             m_options.push_back(opt);
9190             return *this;
9191         }
9192 
operator |=Catch::clara::detail::Parser9193         auto operator|=( Parser const &other ) -> Parser & {
9194             m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9195             m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9196             return *this;
9197         }
9198 
9199         template<typename T>
operator |Catch::clara::detail::Parser9200         auto operator|( T const &other ) const -> Parser {
9201             return Parser( *this ) |= other;
9202         }
9203 
9204         // Forward deprecated interface with '+' instead of '|'
9205         template<typename T>
operator +=Catch::clara::detail::Parser9206         auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9207         template<typename T>
operator +Catch::clara::detail::Parser9208         auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9209 
getHelpColumnsCatch::clara::detail::Parser9210         auto getHelpColumns() const -> std::vector<HelpColumns> {
9211             std::vector<HelpColumns> cols;
9212             for (auto const &o : m_options) {
9213                 auto childCols = o.getHelpColumns();
9214                 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9215             }
9216             return cols;
9217         }
9218 
writeToStreamCatch::clara::detail::Parser9219         void writeToStream( std::ostream &os ) const {
9220             if (!m_exeName.name().empty()) {
9221                 os << "usage:\n" << "  " << m_exeName.name() << " ";
9222                 bool required = true, first = true;
9223                 for( auto const &arg : m_args ) {
9224                     if (first)
9225                         first = false;
9226                     else
9227                         os << " ";
9228                     if( arg.isOptional() && required ) {
9229                         os << "[";
9230                         required = false;
9231                     }
9232                     os << "<" << arg.hint() << ">";
9233                     if( arg.cardinality() == 0 )
9234                         os << " ... ";
9235                 }
9236                 if( !required )
9237                     os << "]";
9238                 if( !m_options.empty() )
9239                     os << " options";
9240                 os << "\n\nwhere options are:" << std::endl;
9241             }
9242 
9243             auto rows = getHelpColumns();
9244             size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9245             size_t optWidth = 0;
9246             for( auto const &cols : rows )
9247                 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9248 
9249             optWidth = (std::min)(optWidth, consoleWidth/2);
9250 
9251             for( auto const &cols : rows ) {
9252                 auto row =
9253                         TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9254                         TextFlow::Spacer(4) +
9255                         TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9256                 os << row << std::endl;
9257             }
9258         }
9259 
operator <<(std::ostream & os,Parser const & parser)9260         friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9261             parser.writeToStream( os );
9262             return os;
9263         }
9264 
validateCatch::clara::detail::Parser9265         auto validate() const -> Result override {
9266             for( auto const &opt : m_options ) {
9267                 auto result = opt.validate();
9268                 if( !result )
9269                     return result;
9270             }
9271             for( auto const &arg : m_args ) {
9272                 auto result = arg.validate();
9273                 if( !result )
9274                     return result;
9275             }
9276             return Result::ok();
9277         }
9278 
9279         using ParserBase::parse;
9280 
parseCatch::clara::detail::Parser9281         auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9282 
9283             struct ParserInfo {
9284                 ParserBase const* parser = nullptr;
9285                 size_t count = 0;
9286             };
9287             const size_t totalParsers = m_options.size() + m_args.size();
9288             assert( totalParsers < 512 );
9289             // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9290             ParserInfo parseInfos[512];
9291 
9292             {
9293                 size_t i = 0;
9294                 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9295                 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9296             }
9297 
9298             m_exeName.set( exeName );
9299 
9300             auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9301             while( result.value().remainingTokens() ) {
9302                 bool tokenParsed = false;
9303 
9304                 for( size_t i = 0; i < totalParsers; ++i ) {
9305                     auto&  parseInfo = parseInfos[i];
9306                     if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9307                         result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9308                         if (!result)
9309                             return result;
9310                         if (result.value().type() != ParseResultType::NoMatch) {
9311                             tokenParsed = true;
9312                             ++parseInfo.count;
9313                             break;
9314                         }
9315                     }
9316                 }
9317 
9318                 if( result.value().type() == ParseResultType::ShortCircuitAll )
9319                     return result;
9320                 if( !tokenParsed )
9321                     return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9322             }
9323             // !TBD Check missing required options
9324             return result;
9325         }
9326     };
9327 
9328     template<typename DerivedT>
9329     template<typename T>
operator |(T const & other) const9330     auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9331         return Parser() | static_cast<DerivedT const &>( *this ) | other;
9332     }
9333 } // namespace detail
9334 
9335 // A Combined parser
9336 using detail::Parser;
9337 
9338 // A parser for options
9339 using detail::Opt;
9340 
9341 // A parser for arguments
9342 using detail::Arg;
9343 
9344 // Wrapper for argc, argv from main()
9345 using detail::Args;
9346 
9347 // Specifies the name of the executable
9348 using detail::ExeName;
9349 
9350 // Convenience wrapper for option parser that specifies the help option
9351 using detail::Help;
9352 
9353 // enum of result types from a parse
9354 using detail::ParseResultType;
9355 
9356 // Result type for parser operation
9357 using detail::ParserResult;
9358 
9359 }} // namespace Catch::clara
9360 
9361 // end clara.hpp
9362 #ifdef __clang__
9363 #pragma clang diagnostic pop
9364 #endif
9365 
9366 // Restore Clara's value for console width, if present
9367 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9368 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9369 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9370 #endif
9371 
9372 // end catch_clara.h
9373 namespace Catch {
9374 
9375     clara::Parser makeCommandLineParser( ConfigData& config );
9376 
9377 } // end namespace Catch
9378 
9379 // end catch_commandline.h
9380 #include <fstream>
9381 #include <ctime>
9382 
9383 namespace Catch {
9384 
makeCommandLineParser(ConfigData & config)9385     clara::Parser makeCommandLineParser( ConfigData& config ) {
9386 
9387         using namespace clara;
9388 
9389         auto const setWarning = [&]( std::string const& warning ) {
9390                 auto warningSet = [&]() {
9391                     if( warning == "NoAssertions" )
9392                         return WarnAbout::NoAssertions;
9393 
9394                     if ( warning == "NoTests" )
9395                         return WarnAbout::NoTests;
9396 
9397                     return WarnAbout::Nothing;
9398                 }();
9399 
9400                 if (warningSet == WarnAbout::Nothing)
9401                     return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9402                 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9403                 return ParserResult::ok( ParseResultType::Matched );
9404             };
9405         auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9406                 std::ifstream f( filename.c_str() );
9407                 if( !f.is_open() )
9408                     return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9409 
9410                 std::string line;
9411                 while( std::getline( f, line ) ) {
9412                     line = trim(line);
9413                     if( !line.empty() && !startsWith( line, '#' ) ) {
9414                         if( !startsWith( line, '"' ) )
9415                             line = '"' + line + '"';
9416                         config.testsOrTags.push_back( line + ',' );
9417                     }
9418                 }
9419                 return ParserResult::ok( ParseResultType::Matched );
9420             };
9421         auto const setTestOrder = [&]( std::string const& order ) {
9422                 if( startsWith( "declared", order ) )
9423                     config.runOrder = RunTests::InDeclarationOrder;
9424                 else if( startsWith( "lexical", order ) )
9425                     config.runOrder = RunTests::InLexicographicalOrder;
9426                 else if( startsWith( "random", order ) )
9427                     config.runOrder = RunTests::InRandomOrder;
9428                 else
9429                     return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9430                 return ParserResult::ok( ParseResultType::Matched );
9431             };
9432         auto const setRngSeed = [&]( std::string const& seed ) {
9433                 if( seed != "time" )
9434                     return clara::detail::convertInto( seed, config.rngSeed );
9435                 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9436                 return ParserResult::ok( ParseResultType::Matched );
9437             };
9438         auto const setColourUsage = [&]( std::string const& useColour ) {
9439                     auto mode = toLower( useColour );
9440 
9441                     if( mode == "yes" )
9442                         config.useColour = UseColour::Yes;
9443                     else if( mode == "no" )
9444                         config.useColour = UseColour::No;
9445                     else if( mode == "auto" )
9446                         config.useColour = UseColour::Auto;
9447                     else
9448                         return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9449                 return ParserResult::ok( ParseResultType::Matched );
9450             };
9451         auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9452                 auto keypressLc = toLower( keypress );
9453                 if( keypressLc == "start" )
9454                     config.waitForKeypress = WaitForKeypress::BeforeStart;
9455                 else if( keypressLc == "exit" )
9456                     config.waitForKeypress = WaitForKeypress::BeforeExit;
9457                 else if( keypressLc == "both" )
9458                     config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9459                 else
9460                     return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
9461             return ParserResult::ok( ParseResultType::Matched );
9462             };
9463         auto const setVerbosity = [&]( std::string const& verbosity ) {
9464             auto lcVerbosity = toLower( verbosity );
9465             if( lcVerbosity == "quiet" )
9466                 config.verbosity = Verbosity::Quiet;
9467             else if( lcVerbosity == "normal" )
9468                 config.verbosity = Verbosity::Normal;
9469             else if( lcVerbosity == "high" )
9470                 config.verbosity = Verbosity::High;
9471             else
9472                 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9473             return ParserResult::ok( ParseResultType::Matched );
9474         };
9475         auto const setReporter = [&]( std::string const& reporter ) {
9476             IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9477 
9478             auto lcReporter = toLower( reporter );
9479             auto result = factories.find( lcReporter );
9480 
9481             if( factories.end() != result )
9482                 config.reporterName = lcReporter;
9483             else
9484                 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9485             return ParserResult::ok( ParseResultType::Matched );
9486         };
9487 
9488         auto cli
9489             = ExeName( config.processName )
9490             | Help( config.showHelp )
9491             | Opt( config.listTests )
9492                 ["-l"]["--list-tests"]
9493                 ( "list all/matching test cases" )
9494             | Opt( config.listTags )
9495                 ["-t"]["--list-tags"]
9496                 ( "list all/matching tags" )
9497             | Opt( config.showSuccessfulTests )
9498                 ["-s"]["--success"]
9499                 ( "include successful tests in output" )
9500             | Opt( config.shouldDebugBreak )
9501                 ["-b"]["--break"]
9502                 ( "break into debugger on failure" )
9503             | Opt( config.noThrow )
9504                 ["-e"]["--nothrow"]
9505                 ( "skip exception tests" )
9506             | Opt( config.showInvisibles )
9507                 ["-i"]["--invisibles"]
9508                 ( "show invisibles (tabs, newlines)" )
9509             | Opt( config.outputFilename, "filename" )
9510                 ["-o"]["--out"]
9511                 ( "output filename" )
9512             | Opt( setReporter, "name" )
9513                 ["-r"]["--reporter"]
9514                 ( "reporter to use (defaults to console)" )
9515             | Opt( config.name, "name" )
9516                 ["-n"]["--name"]
9517                 ( "suite name" )
9518             | Opt( [&]( bool ){ config.abortAfter = 1; } )
9519                 ["-a"]["--abort"]
9520                 ( "abort at first failure" )
9521             | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9522                 ["-x"]["--abortx"]
9523                 ( "abort after x failures" )
9524             | Opt( setWarning, "warning name" )
9525                 ["-w"]["--warn"]
9526                 ( "enable warnings" )
9527             | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9528                 ["-d"]["--durations"]
9529                 ( "show test durations" )
9530             | Opt( loadTestNamesFromFile, "filename" )
9531                 ["-f"]["--input-file"]
9532                 ( "load test names to run from a file" )
9533             | Opt( config.filenamesAsTags )
9534                 ["-#"]["--filenames-as-tags"]
9535                 ( "adds a tag for the filename" )
9536             | Opt( config.sectionsToRun, "section name" )
9537                 ["-c"]["--section"]
9538                 ( "specify section to run" )
9539             | Opt( setVerbosity, "quiet|normal|high" )
9540                 ["-v"]["--verbosity"]
9541                 ( "set output verbosity" )
9542             | Opt( config.listTestNamesOnly )
9543                 ["--list-test-names-only"]
9544                 ( "list all/matching test cases names only" )
9545             | Opt( config.listReporters )
9546                 ["--list-reporters"]
9547                 ( "list all reporters" )
9548             | Opt( setTestOrder, "decl|lex|rand" )
9549                 ["--order"]
9550                 ( "test case order (defaults to decl)" )
9551             | Opt( setRngSeed, "'time'|number" )
9552                 ["--rng-seed"]
9553                 ( "set a specific seed for random numbers" )
9554             | Opt( setColourUsage, "yes|no" )
9555                 ["--use-colour"]
9556                 ( "should output be colourised" )
9557             | Opt( config.libIdentify )
9558                 ["--libidentify"]
9559                 ( "report name and version according to libidentify standard" )
9560             | Opt( setWaitForKeypress, "start|exit|both" )
9561                 ["--wait-for-keypress"]
9562                 ( "waits for a keypress before exiting" )
9563             | Opt( config.benchmarkSamples, "samples" )
9564                 ["--benchmark-samples"]
9565                 ( "number of samples to collect (default: 100)" )
9566             | Opt( config.benchmarkResamples, "resamples" )
9567                 ["--benchmark-resamples"]
9568                 ( "number of resamples for the bootstrap (default: 100000)" )
9569             | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9570                 ["--benchmark-confidence-interval"]
9571                 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9572             | Opt( config.benchmarkNoAnalysis )
9573                 ["--benchmark-no-analysis"]
9574                 ( "perform only measurements; do not perform any analysis" )
9575 			| Arg( config.testsOrTags, "test name|pattern|tags" )
9576                 ( "which test or tests to use" );
9577 
9578         return cli;
9579     }
9580 
9581 } // end namespace Catch
9582 // end catch_commandline.cpp
9583 // start catch_common.cpp
9584 
9585 #include <cstring>
9586 #include <ostream>
9587 
9588 namespace Catch {
9589 
empty() const9590     bool SourceLineInfo::empty() const noexcept {
9591         return file[0] == '\0';
9592     }
operator ==(SourceLineInfo const & other) const9593     bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9594         return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9595     }
operator <(SourceLineInfo const & other) const9596     bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9597         // We can assume that the same file will usually have the same pointer.
9598         // Thus, if the pointers are the same, there is no point in calling the strcmp
9599         return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9600     }
9601 
operator <<(std::ostream & os,SourceLineInfo const & info)9602     std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9603 #ifndef __GNUG__
9604         os << info.file << '(' << info.line << ')';
9605 #else
9606         os << info.file << ':' << info.line;
9607 #endif
9608         return os;
9609     }
9610 
operator +() const9611     std::string StreamEndStop::operator+() const {
9612         return std::string();
9613     }
9614 
9615     NonCopyable::NonCopyable() = default;
9616     NonCopyable::~NonCopyable() = default;
9617 
9618 }
9619 // end catch_common.cpp
9620 // start catch_config.cpp
9621 
9622 namespace Catch {
9623 
Config(ConfigData const & data)9624     Config::Config( ConfigData const& data )
9625     :   m_data( data ),
9626         m_stream( openStream() )
9627     {
9628         TestSpecParser parser(ITagAliasRegistry::get());
9629         if (!data.testsOrTags.empty()) {
9630             m_hasTestFilters = true;
9631             for( auto const& testOrTags : data.testsOrTags )
9632                 parser.parse( testOrTags );
9633         }
9634         m_testSpec = parser.testSpec();
9635     }
9636 
getFilename() const9637     std::string const& Config::getFilename() const {
9638         return m_data.outputFilename ;
9639     }
9640 
listTests() const9641     bool Config::listTests() const          { return m_data.listTests; }
listTestNamesOnly() const9642     bool Config::listTestNamesOnly() const  { return m_data.listTestNamesOnly; }
listTags() const9643     bool Config::listTags() const           { return m_data.listTags; }
listReporters() const9644     bool Config::listReporters() const      { return m_data.listReporters; }
9645 
getProcessName() const9646     std::string Config::getProcessName() const { return m_data.processName; }
getReporterName() const9647     std::string const& Config::getReporterName() const { return m_data.reporterName; }
9648 
getTestsOrTags() const9649     std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
getSectionsToRun() const9650     std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9651 
testSpec() const9652     TestSpec const& Config::testSpec() const { return m_testSpec; }
hasTestFilters() const9653     bool Config::hasTestFilters() const { return m_hasTestFilters; }
9654 
showHelp() const9655     bool Config::showHelp() const { return m_data.showHelp; }
9656 
9657     // IConfig interface
allowThrows() const9658     bool Config::allowThrows() const                   { return !m_data.noThrow; }
stream() const9659     std::ostream& Config::stream() const               { return m_stream->stream(); }
name() const9660     std::string Config::name() const                   { return m_data.name.empty() ? m_data.processName : m_data.name; }
includeSuccessfulResults() const9661     bool Config::includeSuccessfulResults() const      { return m_data.showSuccessfulTests; }
warnAboutMissingAssertions() const9662     bool Config::warnAboutMissingAssertions() const    { return !!(m_data.warnings & WarnAbout::NoAssertions); }
warnAboutNoTests() const9663     bool Config::warnAboutNoTests() const              { return !!(m_data.warnings & WarnAbout::NoTests); }
showDurations() const9664     ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
runOrder() const9665     RunTests::InWhatOrder Config::runOrder() const     { return m_data.runOrder; }
rngSeed() const9666     unsigned int Config::rngSeed() const               { return m_data.rngSeed; }
useColour() const9667     UseColour::YesOrNo Config::useColour() const       { return m_data.useColour; }
shouldDebugBreak() const9668     bool Config::shouldDebugBreak() const              { return m_data.shouldDebugBreak; }
abortAfter() const9669     int Config::abortAfter() const                     { return m_data.abortAfter; }
showInvisibles() const9670     bool Config::showInvisibles() const                { return m_data.showInvisibles; }
verbosity() const9671     Verbosity Config::verbosity() const                { return m_data.verbosity; }
9672 
benchmarkNoAnalysis() const9673     bool Config::benchmarkNoAnalysis() const           { return m_data.benchmarkNoAnalysis; }
benchmarkSamples() const9674     int Config::benchmarkSamples() const               { return m_data.benchmarkSamples; }
benchmarkConfidenceInterval() const9675     double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
benchmarkResamples() const9676     unsigned int Config::benchmarkResamples() const    { return m_data.benchmarkResamples; }
9677 
openStream()9678     IStream const* Config::openStream() {
9679         return Catch::makeStream(m_data.outputFilename);
9680     }
9681 
9682 } // end namespace Catch
9683 // end catch_config.cpp
9684 // start catch_console_colour.cpp
9685 
9686 #if defined(__clang__)
9687 #    pragma clang diagnostic push
9688 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
9689 #endif
9690 
9691 // start catch_errno_guard.h
9692 
9693 namespace Catch {
9694 
9695     class ErrnoGuard {
9696     public:
9697         ErrnoGuard();
9698         ~ErrnoGuard();
9699     private:
9700         int m_oldErrno;
9701     };
9702 
9703 }
9704 
9705 // end catch_errno_guard.h
9706 #include <sstream>
9707 
9708 namespace Catch {
9709     namespace {
9710 
9711         struct IColourImpl {
9712             virtual ~IColourImpl() = default;
9713             virtual void use( Colour::Code _colourCode ) = 0;
9714         };
9715 
9716         struct NoColourImpl : IColourImpl {
useCatch::__anon6485c3de2d11::NoColourImpl9717             void use( Colour::Code ) {}
9718 
instanceCatch::__anon6485c3de2d11::NoColourImpl9719             static IColourImpl* instance() {
9720                 static NoColourImpl s_instance;
9721                 return &s_instance;
9722             }
9723         };
9724 
9725     } // anon namespace
9726 } // namespace Catch
9727 
9728 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
9729 #   ifdef CATCH_PLATFORM_WINDOWS
9730 #       define CATCH_CONFIG_COLOUR_WINDOWS
9731 #   else
9732 #       define CATCH_CONFIG_COLOUR_ANSI
9733 #   endif
9734 #endif
9735 
9736 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
9737 
9738 namespace Catch {
9739 namespace {
9740 
9741     class Win32ColourImpl : public IColourImpl {
9742     public:
Win32ColourImpl()9743         Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
9744         {
9745             CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
9746             GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
9747             originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
9748             originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
9749         }
9750 
use(Colour::Code _colourCode)9751         void use( Colour::Code _colourCode ) override {
9752             switch( _colourCode ) {
9753                 case Colour::None:      return setTextAttribute( originalForegroundAttributes );
9754                 case Colour::White:     return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
9755                 case Colour::Red:       return setTextAttribute( FOREGROUND_RED );
9756                 case Colour::Green:     return setTextAttribute( FOREGROUND_GREEN );
9757                 case Colour::Blue:      return setTextAttribute( FOREGROUND_BLUE );
9758                 case Colour::Cyan:      return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
9759                 case Colour::Yellow:    return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
9760                 case Colour::Grey:      return setTextAttribute( 0 );
9761 
9762                 case Colour::LightGrey:     return setTextAttribute( FOREGROUND_INTENSITY );
9763                 case Colour::BrightRed:     return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
9764                 case Colour::BrightGreen:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
9765                 case Colour::BrightWhite:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
9766                 case Colour::BrightYellow:  return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
9767 
9768                 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
9769 
9770                 default:
9771                     CATCH_ERROR( "Unknown colour requested" );
9772             }
9773         }
9774 
9775     private:
setTextAttribute(WORD _textAttribute)9776         void setTextAttribute( WORD _textAttribute ) {
9777             SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
9778         }
9779         HANDLE stdoutHandle;
9780         WORD originalForegroundAttributes;
9781         WORD originalBackgroundAttributes;
9782     };
9783 
platformColourInstance()9784     IColourImpl* platformColourInstance() {
9785         static Win32ColourImpl s_instance;
9786 
9787         IConfigPtr config = getCurrentContext().getConfig();
9788         UseColour::YesOrNo colourMode = config
9789             ? config->useColour()
9790             : UseColour::Auto;
9791         if( colourMode == UseColour::Auto )
9792             colourMode = UseColour::Yes;
9793         return colourMode == UseColour::Yes
9794             ? &s_instance
9795             : NoColourImpl::instance();
9796     }
9797 
9798 } // end anon namespace
9799 } // end namespace Catch
9800 
9801 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
9802 
9803 #include <unistd.h>
9804 
9805 namespace Catch {
9806 namespace {
9807 
9808     // use POSIX/ ANSI console terminal codes
9809     // Thanks to Adam Strzelecki for original contribution
9810     // (http://github.com/nanoant)
9811     // https://github.com/philsquared/Catch/pull/131
9812     class PosixColourImpl : public IColourImpl {
9813     public:
use(Colour::Code _colourCode)9814         void use( Colour::Code _colourCode ) override {
9815             switch( _colourCode ) {
9816                 case Colour::None:
9817                 case Colour::White:     return setColour( "[0m" );
9818                 case Colour::Red:       return setColour( "[0;31m" );
9819                 case Colour::Green:     return setColour( "[0;32m" );
9820                 case Colour::Blue:      return setColour( "[0;34m" );
9821                 case Colour::Cyan:      return setColour( "[0;36m" );
9822                 case Colour::Yellow:    return setColour( "[0;33m" );
9823                 case Colour::Grey:      return setColour( "[1;30m" );
9824 
9825                 case Colour::LightGrey:     return setColour( "[0;37m" );
9826                 case Colour::BrightRed:     return setColour( "[1;31m" );
9827                 case Colour::BrightGreen:   return setColour( "[1;32m" );
9828                 case Colour::BrightWhite:   return setColour( "[1;37m" );
9829                 case Colour::BrightYellow:  return setColour( "[1;33m" );
9830 
9831                 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
9832                 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
9833             }
9834         }
instance()9835         static IColourImpl* instance() {
9836             static PosixColourImpl s_instance;
9837             return &s_instance;
9838         }
9839 
9840     private:
setColour(const char * _escapeCode)9841         void setColour( const char* _escapeCode ) {
9842             getCurrentContext().getConfig()->stream()
9843                 << '\033' << _escapeCode;
9844         }
9845     };
9846 
useColourOnPlatform()9847     bool useColourOnPlatform() {
9848         return
9849 #ifdef CATCH_PLATFORM_MAC
9850             !isDebuggerActive() &&
9851 #endif
9852 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
9853             isatty(STDOUT_FILENO)
9854 #else
9855             false
9856 #endif
9857             ;
9858     }
platformColourInstance()9859     IColourImpl* platformColourInstance() {
9860         ErrnoGuard guard;
9861         IConfigPtr config = getCurrentContext().getConfig();
9862         UseColour::YesOrNo colourMode = config
9863             ? config->useColour()
9864             : UseColour::Auto;
9865         if( colourMode == UseColour::Auto )
9866             colourMode = useColourOnPlatform()
9867                 ? UseColour::Yes
9868                 : UseColour::No;
9869         return colourMode == UseColour::Yes
9870             ? PosixColourImpl::instance()
9871             : NoColourImpl::instance();
9872     }
9873 
9874 } // end anon namespace
9875 } // end namespace Catch
9876 
9877 #else  // not Windows or ANSI ///////////////////////////////////////////////
9878 
9879 namespace Catch {
9880 
platformColourInstance()9881     static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
9882 
9883 } // end namespace Catch
9884 
9885 #endif // Windows/ ANSI/ None
9886 
9887 namespace Catch {
9888 
Colour(Code _colourCode)9889     Colour::Colour( Code _colourCode ) { use( _colourCode ); }
Colour(Colour && rhs)9890     Colour::Colour( Colour&& rhs ) noexcept {
9891         m_moved = rhs.m_moved;
9892         rhs.m_moved = true;
9893     }
operator =(Colour && rhs)9894     Colour& Colour::operator=( Colour&& rhs ) noexcept {
9895         m_moved = rhs.m_moved;
9896         rhs.m_moved  = true;
9897         return *this;
9898     }
9899 
~Colour()9900     Colour::~Colour(){ if( !m_moved ) use( None ); }
9901 
use(Code _colourCode)9902     void Colour::use( Code _colourCode ) {
9903         static IColourImpl* impl = platformColourInstance();
9904         // Strictly speaking, this cannot possibly happen.
9905         // However, under some conditions it does happen (see #1626),
9906         // and this change is small enough that we can let practicality
9907         // triumph over purity in this case.
9908         if (impl != NULL) {
9909             impl->use( _colourCode );
9910         }
9911     }
9912 
operator <<(std::ostream & os,Colour const &)9913     std::ostream& operator << ( std::ostream& os, Colour const& ) {
9914         return os;
9915     }
9916 
9917 } // end namespace Catch
9918 
9919 #if defined(__clang__)
9920 #    pragma clang diagnostic pop
9921 #endif
9922 
9923 // end catch_console_colour.cpp
9924 // start catch_context.cpp
9925 
9926 namespace Catch {
9927 
9928     class Context : public IMutableContext, NonCopyable {
9929 
9930     public: // IContext
getResultCapture()9931         IResultCapture* getResultCapture() override {
9932             return m_resultCapture;
9933         }
getRunner()9934         IRunner* getRunner() override {
9935             return m_runner;
9936         }
9937 
getConfig() const9938         IConfigPtr const& getConfig() const override {
9939             return m_config;
9940         }
9941 
9942         ~Context() override;
9943 
9944     public: // IMutableContext
setResultCapture(IResultCapture * resultCapture)9945         void setResultCapture( IResultCapture* resultCapture ) override {
9946             m_resultCapture = resultCapture;
9947         }
setRunner(IRunner * runner)9948         void setRunner( IRunner* runner ) override {
9949             m_runner = runner;
9950         }
setConfig(IConfigPtr const & config)9951         void setConfig( IConfigPtr const& config ) override {
9952             m_config = config;
9953         }
9954 
9955         friend IMutableContext& getCurrentMutableContext();
9956 
9957     private:
9958         IConfigPtr m_config;
9959         IRunner* m_runner = nullptr;
9960         IResultCapture* m_resultCapture = nullptr;
9961     };
9962 
9963     IMutableContext *IMutableContext::currentContext = nullptr;
9964 
createContext()9965     void IMutableContext::createContext()
9966     {
9967         currentContext = new Context();
9968     }
9969 
cleanUpContext()9970     void cleanUpContext() {
9971         delete IMutableContext::currentContext;
9972         IMutableContext::currentContext = nullptr;
9973     }
9974     IContext::~IContext() = default;
9975     IMutableContext::~IMutableContext() = default;
9976     Context::~Context() = default;
9977 }
9978 // end catch_context.cpp
9979 // start catch_debug_console.cpp
9980 
9981 // start catch_debug_console.h
9982 
9983 #include <string>
9984 
9985 namespace Catch {
9986     void writeToDebugConsole( std::string const& text );
9987 }
9988 
9989 // end catch_debug_console.h
9990 #if defined(__ANDROID__)
9991 #include <android/log.h>
9992 
9993     namespace Catch {
writeToDebugConsole(std::string const & text)9994         void writeToDebugConsole( std::string const& text ) {
9995             __android_log_print( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
9996         }
9997     }
9998 
9999 #elif defined(CATCH_PLATFORM_WINDOWS)
10000 
10001     namespace Catch {
writeToDebugConsole(std::string const & text)10002         void writeToDebugConsole( std::string const& text ) {
10003             ::OutputDebugStringA( text.c_str() );
10004         }
10005     }
10006 
10007 #else
10008 
10009     namespace Catch {
writeToDebugConsole(std::string const & text)10010         void writeToDebugConsole( std::string const& text ) {
10011             // !TBD: Need a version for Mac/ XCode and other IDEs
10012             Catch::cout() << text;
10013         }
10014     }
10015 
10016 #endif // Platform
10017 // end catch_debug_console.cpp
10018 // start catch_debugger.cpp
10019 
10020 #ifdef CATCH_PLATFORM_MAC
10021 
10022 #  include <assert.h>
10023 #  include <stdbool.h>
10024 #  include <sys/types.h>
10025 #  include <unistd.h>
10026 #  include <cstddef>
10027 #  include <ostream>
10028 
10029 #ifdef __apple_build_version__
10030     // These headers will only compile with AppleClang (XCode)
10031     // For other compilers (Clang, GCC, ... ) we need to exclude them
10032 #  include <sys/sysctl.h>
10033 #endif
10034 
10035     namespace Catch {
10036         #ifdef __apple_build_version__
10037         // The following function is taken directly from the following technical note:
10038         // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10039 
10040         // Returns true if the current process is being debugged (either
10041         // running under the debugger or has a debugger attached post facto).
isDebuggerActive()10042         bool isDebuggerActive(){
10043             int                 mib[4];
10044             struct kinfo_proc   info;
10045             std::size_t         size;
10046 
10047             // Initialize the flags so that, if sysctl fails for some bizarre
10048             // reason, we get a predictable result.
10049 
10050             info.kp_proc.p_flag = 0;
10051 
10052             // Initialize mib, which tells sysctl the info we want, in this case
10053             // we're looking for information about a specific process ID.
10054 
10055             mib[0] = CTL_KERN;
10056             mib[1] = KERN_PROC;
10057             mib[2] = KERN_PROC_PID;
10058             mib[3] = getpid();
10059 
10060             // Call sysctl.
10061 
10062             size = sizeof(info);
10063             if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10064                 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10065                 return false;
10066             }
10067 
10068             // We're being debugged if the P_TRACED flag is set.
10069 
10070             return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10071         }
10072         #else
10073         bool isDebuggerActive() {
10074             // We need to find another way to determine this for non-appleclang compilers on macOS
10075             return false;
10076         }
10077         #endif
10078     } // namespace Catch
10079 
10080 #elif defined(CATCH_PLATFORM_LINUX)
10081     #include <fstream>
10082     #include <string>
10083 
10084     namespace Catch{
10085         // The standard POSIX way of detecting a debugger is to attempt to
10086         // ptrace() the process, but this needs to be done from a child and not
10087         // this process itself to still allow attaching to this process later
10088         // if wanted, so is rather heavy. Under Linux we have the PID of the
10089         // "debugger" (which doesn't need to be gdb, of course, it could also
10090         // be strace, for example) in /proc/$PID/status, so just get it from
10091         // there instead.
isDebuggerActive()10092         bool isDebuggerActive(){
10093             // Libstdc++ has a bug, where std::ifstream sets errno to 0
10094             // This way our users can properly assert over errno values
10095             ErrnoGuard guard;
10096             std::ifstream in("/proc/self/status");
10097             for( std::string line; std::getline(in, line); ) {
10098                 static const int PREFIX_LEN = 11;
10099                 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10100                     // We're traced if the PID is not 0 and no other PID starts
10101                     // with 0 digit, so it's enough to check for just a single
10102                     // character.
10103                     return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10104                 }
10105             }
10106 
10107             return false;
10108         }
10109     } // namespace Catch
10110 #elif defined(_MSC_VER)
10111     extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10112     namespace Catch {
isDebuggerActive()10113         bool isDebuggerActive() {
10114             return IsDebuggerPresent() != 0;
10115         }
10116     }
10117 #elif defined(__MINGW32__)
10118     extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10119     namespace Catch {
isDebuggerActive()10120         bool isDebuggerActive() {
10121             return IsDebuggerPresent() != 0;
10122         }
10123     }
10124 #else
10125     namespace Catch {
isDebuggerActive()10126        bool isDebuggerActive() { return false; }
10127     }
10128 #endif // Platform
10129 // end catch_debugger.cpp
10130 // start catch_decomposer.cpp
10131 
10132 namespace Catch {
10133 
10134     ITransientExpression::~ITransientExpression() = default;
10135 
formatReconstructedExpression(std::ostream & os,std::string const & lhs,StringRef op,std::string const & rhs)10136     void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10137         if( lhs.size() + rhs.size() < 40 &&
10138                 lhs.find('\n') == std::string::npos &&
10139                 rhs.find('\n') == std::string::npos )
10140             os << lhs << " " << op << " " << rhs;
10141         else
10142             os << lhs << "\n" << op << "\n" << rhs;
10143     }
10144 }
10145 // end catch_decomposer.cpp
10146 // start catch_enforce.cpp
10147 
10148 #include <stdexcept>
10149 
10150 namespace Catch {
10151 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10152     [[noreturn]]
throw_exception(std::exception const & e)10153     void throw_exception(std::exception const& e) {
10154         Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10155                       << "The message was: " << e.what() << '\n';
10156         std::terminate();
10157     }
10158 #endif
10159 
10160     [[noreturn]]
throw_logic_error(std::string const & msg)10161     void throw_logic_error(std::string const& msg) {
10162         throw_exception(std::logic_error(msg));
10163     }
10164 
10165     [[noreturn]]
throw_domain_error(std::string const & msg)10166     void throw_domain_error(std::string const& msg) {
10167         throw_exception(std::domain_error(msg));
10168     }
10169 
10170     [[noreturn]]
throw_runtime_error(std::string const & msg)10171     void throw_runtime_error(std::string const& msg) {
10172         throw_exception(std::runtime_error(msg));
10173     }
10174 
10175 } // namespace Catch;
10176 // end catch_enforce.cpp
10177 // start catch_enum_values_registry.cpp
10178 // start catch_enum_values_registry.h
10179 
10180 #include <vector>
10181 #include <memory>
10182 
10183 namespace Catch {
10184 
10185     namespace Detail {
10186 
10187         std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10188 
10189         class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10190 
10191             std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10192 
10193             EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10194         };
10195 
10196         std::vector<std::string> parseEnums( StringRef enums );
10197 
10198     } // Detail
10199 
10200 } // Catch
10201 
10202 // end catch_enum_values_registry.h
10203 
10204 #include <map>
10205 #include <cassert>
10206 
10207 namespace Catch {
10208 
~IMutableEnumValuesRegistry()10209     IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10210 
10211     namespace Detail {
10212 
parseEnums(StringRef enums)10213         std::vector<std::string> parseEnums( StringRef enums ) {
10214             auto enumValues = splitStringRef( enums, ',' );
10215             std::vector<std::string> parsed;
10216             parsed.reserve( enumValues.size() );
10217             for( auto const& enumValue : enumValues ) {
10218                 auto identifiers = splitStringRef( enumValue, ':' );
10219                 parsed.push_back( Catch::trim( identifiers.back() ) );
10220             }
10221             return parsed;
10222         }
10223 
~EnumInfo()10224         EnumInfo::~EnumInfo() {}
10225 
lookup(int value) const10226         StringRef EnumInfo::lookup( int value ) const {
10227             for( auto const& valueToName : m_values ) {
10228                 if( valueToName.first == value )
10229                     return valueToName.second;
10230             }
10231             return "{** unexpected enum value **}";
10232         }
10233 
makeEnumInfo(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10234         std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10235             std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10236             enumInfo->m_name = enumName;
10237             enumInfo->m_values.reserve( values.size() );
10238 
10239             const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10240             assert( valueNames.size() == values.size() );
10241             std::size_t i = 0;
10242             for( auto value : values )
10243                 enumInfo->m_values.push_back({ value, valueNames[i++] });
10244 
10245             return enumInfo;
10246         }
10247 
registerEnum(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10248         EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10249             auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
10250             EnumInfo* raw = enumInfo.get();
10251             m_enumInfos.push_back( std::move( enumInfo ) );
10252             return *raw;
10253         }
10254 
10255     } // Detail
10256 } // Catch
10257 
10258 // end catch_enum_values_registry.cpp
10259 // start catch_errno_guard.cpp
10260 
10261 #include <cerrno>
10262 
10263 namespace Catch {
ErrnoGuard()10264         ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
~ErrnoGuard()10265         ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10266 }
10267 // end catch_errno_guard.cpp
10268 // start catch_exception_translator_registry.cpp
10269 
10270 // start catch_exception_translator_registry.h
10271 
10272 #include <vector>
10273 #include <string>
10274 #include <memory>
10275 
10276 namespace Catch {
10277 
10278     class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10279     public:
10280         ~ExceptionTranslatorRegistry();
10281         virtual void registerTranslator( const IExceptionTranslator* translator );
10282         std::string translateActiveException() const override;
10283         std::string tryTranslators() const;
10284 
10285     private:
10286         std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10287     };
10288 }
10289 
10290 // end catch_exception_translator_registry.h
10291 #ifdef __OBJC__
10292 #import "Foundation/Foundation.h"
10293 #endif
10294 
10295 namespace Catch {
10296 
~ExceptionTranslatorRegistry()10297     ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10298     }
10299 
registerTranslator(const IExceptionTranslator * translator)10300     void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10301         m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10302     }
10303 
10304 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
translateActiveException() const10305     std::string ExceptionTranslatorRegistry::translateActiveException() const {
10306         try {
10307 #ifdef __OBJC__
10308             // In Objective-C try objective-c exceptions first
10309             @try {
10310                 return tryTranslators();
10311             }
10312             @catch (NSException *exception) {
10313                 return Catch::Detail::stringify( [exception description] );
10314             }
10315 #else
10316             // Compiling a mixed mode project with MSVC means that CLR
10317             // exceptions will be caught in (...) as well. However, these
10318             // do not fill-in std::current_exception and thus lead to crash
10319             // when attempting rethrow.
10320             // /EHa switch also causes structured exceptions to be caught
10321             // here, but they fill-in current_exception properly, so
10322             // at worst the output should be a little weird, instead of
10323             // causing a crash.
10324             if (std::current_exception() == nullptr) {
10325                 return "Non C++ exception. Possibly a CLR exception.";
10326             }
10327             return tryTranslators();
10328 #endif
10329         }
10330         catch( TestFailureException& ) {
10331             std::rethrow_exception(std::current_exception());
10332         }
10333         catch( std::exception& ex ) {
10334             return ex.what();
10335         }
10336         catch( std::string& msg ) {
10337             return msg;
10338         }
10339         catch( const char* msg ) {
10340             return msg;
10341         }
10342         catch(...) {
10343             return "Unknown exception";
10344         }
10345     }
10346 
tryTranslators() const10347     std::string ExceptionTranslatorRegistry::tryTranslators() const {
10348         if (m_translators.empty()) {
10349             std::rethrow_exception(std::current_exception());
10350         } else {
10351             return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10352         }
10353     }
10354 
10355 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
translateActiveException() const10356     std::string ExceptionTranslatorRegistry::translateActiveException() const {
10357         CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10358     }
10359 
tryTranslators() const10360     std::string ExceptionTranslatorRegistry::tryTranslators() const {
10361         CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10362     }
10363 #endif
10364 
10365 }
10366 // end catch_exception_translator_registry.cpp
10367 // start catch_fatal_condition.cpp
10368 
10369 #if defined(__GNUC__)
10370 #    pragma GCC diagnostic push
10371 #    pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10372 #endif
10373 
10374 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10375 
10376 namespace {
10377     // Report the error condition
reportFatal(char const * const message)10378     void reportFatal( char const * const message ) {
10379         Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10380     }
10381 }
10382 
10383 #endif // signals/SEH handling
10384 
10385 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10386 
10387 namespace Catch {
10388     struct SignalDefs { DWORD id; const char* name; };
10389 
10390     // There is no 1-1 mapping between signals and windows exceptions.
10391     // Windows can easily distinguish between SO and SigSegV,
10392     // but SigInt, SigTerm, etc are handled differently.
10393     static SignalDefs signalDefs[] = {
10394         { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION),  "SIGILL - Illegal instruction signal" },
10395         { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10396         { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10397         { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10398     };
10399 
handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo)10400     LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10401         for (auto const& def : signalDefs) {
10402             if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10403                 reportFatal(def.name);
10404             }
10405         }
10406         // If its not an exception we care about, pass it along.
10407         // This stops us from eating debugger breaks etc.
10408         return EXCEPTION_CONTINUE_SEARCH;
10409     }
10410 
FatalConditionHandler()10411     FatalConditionHandler::FatalConditionHandler() {
10412         isSet = true;
10413         // 32k seems enough for Catch to handle stack overflow,
10414         // but the value was found experimentally, so there is no strong guarantee
10415         guaranteeSize = 32 * 1024;
10416         exceptionHandlerHandle = nullptr;
10417         // Register as first handler in current chain
10418         exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10419         // Pass in guarantee size to be filled
10420         SetThreadStackGuarantee(&guaranteeSize);
10421     }
10422 
reset()10423     void FatalConditionHandler::reset() {
10424         if (isSet) {
10425             RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10426             SetThreadStackGuarantee(&guaranteeSize);
10427             exceptionHandlerHandle = nullptr;
10428             isSet = false;
10429         }
10430     }
10431 
~FatalConditionHandler()10432     FatalConditionHandler::~FatalConditionHandler() {
10433         reset();
10434     }
10435 
10436 bool FatalConditionHandler::isSet = false;
10437 ULONG FatalConditionHandler::guaranteeSize = 0;
10438 PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
10439 
10440 } // namespace Catch
10441 
10442 #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
10443 
10444 namespace Catch {
10445 
10446     struct SignalDefs {
10447         int id;
10448         const char* name;
10449     };
10450 
10451     // 32kb for the alternate stack seems to be sufficient. However, this value
10452     // is experimentally determined, so that's not guaranteed.
10453     static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10454 
10455     static SignalDefs signalDefs[] = {
10456         { SIGINT,  "SIGINT - Terminal interrupt signal" },
10457         { SIGILL,  "SIGILL - Illegal instruction signal" },
10458         { SIGFPE,  "SIGFPE - Floating point error signal" },
10459         { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10460         { SIGTERM, "SIGTERM - Termination request signal" },
10461         { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10462     };
10463 
handleSignal(int sig)10464     void FatalConditionHandler::handleSignal( int sig ) {
10465         char const * name = "<unknown signal>";
10466         for (auto const& def : signalDefs) {
10467             if (sig == def.id) {
10468                 name = def.name;
10469                 break;
10470             }
10471         }
10472         reset();
10473         reportFatal(name);
10474         raise( sig );
10475     }
10476 
FatalConditionHandler()10477     FatalConditionHandler::FatalConditionHandler() {
10478         isSet = true;
10479         stack_t sigStack;
10480         sigStack.ss_sp = altStackMem;
10481         sigStack.ss_size = sigStackSize;
10482         sigStack.ss_flags = 0;
10483         sigaltstack(&sigStack, &oldSigStack);
10484         struct sigaction sa = { };
10485 
10486         sa.sa_handler = handleSignal;
10487         sa.sa_flags = SA_ONSTACK;
10488         for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10489             sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10490         }
10491     }
10492 
~FatalConditionHandler()10493     FatalConditionHandler::~FatalConditionHandler() {
10494         reset();
10495     }
10496 
reset()10497     void FatalConditionHandler::reset() {
10498         if( isSet ) {
10499             // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
10500             for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
10501                 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10502             }
10503             // Return the old stack
10504             sigaltstack(&oldSigStack, nullptr);
10505             isSet = false;
10506         }
10507     }
10508 
10509     bool FatalConditionHandler::isSet = false;
10510     struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10511     stack_t FatalConditionHandler::oldSigStack = {};
10512     char FatalConditionHandler::altStackMem[sigStackSize] = {};
10513 
10514 } // namespace Catch
10515 
10516 #else
10517 
10518 namespace Catch {
reset()10519     void FatalConditionHandler::reset() {}
10520 }
10521 
10522 #endif // signals/SEH handling
10523 
10524 #if defined(__GNUC__)
10525 #    pragma GCC diagnostic pop
10526 #endif
10527 // end catch_fatal_condition.cpp
10528 // start catch_generators.cpp
10529 
10530 // start catch_random_number_generator.h
10531 
10532 #include <algorithm>
10533 #include <random>
10534 
10535 namespace Catch {
10536 
10537     struct IConfig;
10538 
10539     std::mt19937& rng();
10540     void seedRng( IConfig const& config );
10541     unsigned int rngSeed();
10542 
10543 }
10544 
10545 // end catch_random_number_generator.h
10546 #include <limits>
10547 #include <set>
10548 
10549 namespace Catch {
10550 
~IGeneratorTracker()10551 IGeneratorTracker::~IGeneratorTracker() {}
10552 
what() const10553 const char* GeneratorException::what() const noexcept {
10554     return m_msg;
10555 }
10556 
10557 namespace Generators {
10558 
~GeneratorUntypedBase()10559     GeneratorUntypedBase::~GeneratorUntypedBase() {}
10560 
acquireGeneratorTracker(SourceLineInfo const & lineInfo)10561     auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10562         return getResultCapture().acquireGeneratorTracker( lineInfo );
10563     }
10564 
10565 } // namespace Generators
10566 } // namespace Catch
10567 // end catch_generators.cpp
10568 // start catch_interfaces_capture.cpp
10569 
10570 namespace Catch {
10571     IResultCapture::~IResultCapture() = default;
10572 }
10573 // end catch_interfaces_capture.cpp
10574 // start catch_interfaces_config.cpp
10575 
10576 namespace Catch {
10577     IConfig::~IConfig() = default;
10578 }
10579 // end catch_interfaces_config.cpp
10580 // start catch_interfaces_exception.cpp
10581 
10582 namespace Catch {
10583     IExceptionTranslator::~IExceptionTranslator() = default;
10584     IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
10585 }
10586 // end catch_interfaces_exception.cpp
10587 // start catch_interfaces_registry_hub.cpp
10588 
10589 namespace Catch {
10590     IRegistryHub::~IRegistryHub() = default;
10591     IMutableRegistryHub::~IMutableRegistryHub() = default;
10592 }
10593 // end catch_interfaces_registry_hub.cpp
10594 // start catch_interfaces_reporter.cpp
10595 
10596 // start catch_reporter_listening.h
10597 
10598 namespace Catch {
10599 
10600     class ListeningReporter : public IStreamingReporter {
10601         using Reporters = std::vector<IStreamingReporterPtr>;
10602         Reporters m_listeners;
10603         IStreamingReporterPtr m_reporter = nullptr;
10604         ReporterPreferences m_preferences;
10605 
10606     public:
10607         ListeningReporter();
10608 
10609         void addListener( IStreamingReporterPtr&& listener );
10610         void addReporter( IStreamingReporterPtr&& reporter );
10611 
10612     public: // IStreamingReporter
10613 
10614         ReporterPreferences getPreferences() const override;
10615 
10616         void noMatchingTestCases( std::string const& spec ) override;
10617 
10618         static std::set<Verbosity> getSupportedVerbosities();
10619 
10620 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
10621         void benchmarkPreparing(std::string const& name) override;
10622         void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
10623         void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
10624         void benchmarkFailed(std::string const&) override;
10625 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
10626 
10627         void testRunStarting( TestRunInfo const& testRunInfo ) override;
10628         void testGroupStarting( GroupInfo const& groupInfo ) override;
10629         void testCaseStarting( TestCaseInfo const& testInfo ) override;
10630         void sectionStarting( SectionInfo const& sectionInfo ) override;
10631         void assertionStarting( AssertionInfo const& assertionInfo ) override;
10632 
10633         // The return value indicates if the messages buffer should be cleared:
10634         bool assertionEnded( AssertionStats const& assertionStats ) override;
10635         void sectionEnded( SectionStats const& sectionStats ) override;
10636         void testCaseEnded( TestCaseStats const& testCaseStats ) override;
10637         void testGroupEnded( TestGroupStats const& testGroupStats ) override;
10638         void testRunEnded( TestRunStats const& testRunStats ) override;
10639 
10640         void skipTest( TestCaseInfo const& testInfo ) override;
10641         bool isMulti() const override;
10642 
10643     };
10644 
10645 } // end namespace Catch
10646 
10647 // end catch_reporter_listening.h
10648 namespace Catch {
10649 
ReporterConfig(IConfigPtr const & _fullConfig)10650     ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
10651     :   m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
10652 
ReporterConfig(IConfigPtr const & _fullConfig,std::ostream & _stream)10653     ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
10654     :   m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
10655 
stream() const10656     std::ostream& ReporterConfig::stream() const { return *m_stream; }
fullConfig() const10657     IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
10658 
TestRunInfo(std::string const & _name)10659     TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
10660 
GroupInfo(std::string const & _name,std::size_t _groupIndex,std::size_t _groupsCount)10661     GroupInfo::GroupInfo(  std::string const& _name,
10662                            std::size_t _groupIndex,
10663                            std::size_t _groupsCount )
10664     :   name( _name ),
10665         groupIndex( _groupIndex ),
10666         groupsCounts( _groupsCount )
10667     {}
10668 
AssertionStats(AssertionResult const & _assertionResult,std::vector<MessageInfo> const & _infoMessages,Totals const & _totals)10669      AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
10670                                      std::vector<MessageInfo> const& _infoMessages,
10671                                      Totals const& _totals )
10672     :   assertionResult( _assertionResult ),
10673         infoMessages( _infoMessages ),
10674         totals( _totals )
10675     {
10676         assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
10677 
10678         if( assertionResult.hasMessage() ) {
10679             // Copy message into messages list.
10680             // !TBD This should have been done earlier, somewhere
10681             MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
10682             builder << assertionResult.getMessage();
10683             builder.m_info.message = builder.m_stream.str();
10684 
10685             infoMessages.push_back( builder.m_info );
10686         }
10687     }
10688 
10689      AssertionStats::~AssertionStats() = default;
10690 
SectionStats(SectionInfo const & _sectionInfo,Counts const & _assertions,double _durationInSeconds,bool _missingAssertions)10691     SectionStats::SectionStats(  SectionInfo const& _sectionInfo,
10692                                  Counts const& _assertions,
10693                                  double _durationInSeconds,
10694                                  bool _missingAssertions )
10695     :   sectionInfo( _sectionInfo ),
10696         assertions( _assertions ),
10697         durationInSeconds( _durationInSeconds ),
10698         missingAssertions( _missingAssertions )
10699     {}
10700 
10701     SectionStats::~SectionStats() = default;
10702 
TestCaseStats(TestCaseInfo const & _testInfo,Totals const & _totals,std::string const & _stdOut,std::string const & _stdErr,bool _aborting)10703     TestCaseStats::TestCaseStats(  TestCaseInfo const& _testInfo,
10704                                    Totals const& _totals,
10705                                    std::string const& _stdOut,
10706                                    std::string const& _stdErr,
10707                                    bool _aborting )
10708     : testInfo( _testInfo ),
10709         totals( _totals ),
10710         stdOut( _stdOut ),
10711         stdErr( _stdErr ),
10712         aborting( _aborting )
10713     {}
10714 
10715     TestCaseStats::~TestCaseStats() = default;
10716 
TestGroupStats(GroupInfo const & _groupInfo,Totals const & _totals,bool _aborting)10717     TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
10718                                     Totals const& _totals,
10719                                     bool _aborting )
10720     :   groupInfo( _groupInfo ),
10721         totals( _totals ),
10722         aborting( _aborting )
10723     {}
10724 
TestGroupStats(GroupInfo const & _groupInfo)10725     TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
10726     :   groupInfo( _groupInfo ),
10727         aborting( false )
10728     {}
10729 
10730     TestGroupStats::~TestGroupStats() = default;
10731 
TestRunStats(TestRunInfo const & _runInfo,Totals const & _totals,bool _aborting)10732     TestRunStats::TestRunStats(   TestRunInfo const& _runInfo,
10733                     Totals const& _totals,
10734                     bool _aborting )
10735     :   runInfo( _runInfo ),
10736         totals( _totals ),
10737         aborting( _aborting )
10738     {}
10739 
10740     TestRunStats::~TestRunStats() = default;
10741 
fatalErrorEncountered(StringRef)10742     void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
isMulti() const10743     bool IStreamingReporter::isMulti() const { return false; }
10744 
10745     IReporterFactory::~IReporterFactory() = default;
10746     IReporterRegistry::~IReporterRegistry() = default;
10747 
10748 } // end namespace Catch
10749 // end catch_interfaces_reporter.cpp
10750 // start catch_interfaces_runner.cpp
10751 
10752 namespace Catch {
10753     IRunner::~IRunner() = default;
10754 }
10755 // end catch_interfaces_runner.cpp
10756 // start catch_interfaces_testcase.cpp
10757 
10758 namespace Catch {
10759     ITestInvoker::~ITestInvoker() = default;
10760     ITestCaseRegistry::~ITestCaseRegistry() = default;
10761 }
10762 // end catch_interfaces_testcase.cpp
10763 // start catch_leak_detector.cpp
10764 
10765 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
10766 #include <crtdbg.h>
10767 
10768 namespace Catch {
10769 
LeakDetector()10770     LeakDetector::LeakDetector() {
10771         int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
10772         flag |= _CRTDBG_LEAK_CHECK_DF;
10773         flag |= _CRTDBG_ALLOC_MEM_DF;
10774         _CrtSetDbgFlag(flag);
10775         _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
10776         _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
10777         // Change this to leaking allocation's number to break there
10778         _CrtSetBreakAlloc(-1);
10779     }
10780 }
10781 
10782 #else
10783 
LeakDetector()10784     Catch::LeakDetector::LeakDetector() {}
10785 
10786 #endif
10787 
~LeakDetector()10788 Catch::LeakDetector::~LeakDetector() {
10789     Catch::cleanUp();
10790 }
10791 // end catch_leak_detector.cpp
10792 // start catch_list.cpp
10793 
10794 // start catch_list.h
10795 
10796 #include <set>
10797 
10798 namespace Catch {
10799 
10800     std::size_t listTests( Config const& config );
10801 
10802     std::size_t listTestsNamesOnly( Config const& config );
10803 
10804     struct TagInfo {
10805         void add( std::string const& spelling );
10806         std::string all() const;
10807 
10808         std::set<std::string> spellings;
10809         std::size_t count = 0;
10810     };
10811 
10812     std::size_t listTags( Config const& config );
10813 
10814     std::size_t listReporters();
10815 
10816     Option<std::size_t> list( std::shared_ptr<Config> const& config );
10817 
10818 } // end namespace Catch
10819 
10820 // end catch_list.h
10821 // start catch_text.h
10822 
10823 namespace Catch {
10824     using namespace clara::TextFlow;
10825 }
10826 
10827 // end catch_text.h
10828 #include <limits>
10829 #include <algorithm>
10830 #include <iomanip>
10831 
10832 namespace Catch {
10833 
listTests(Config const & config)10834     std::size_t listTests( Config const& config ) {
10835         TestSpec testSpec = config.testSpec();
10836         if( config.hasTestFilters() )
10837             Catch::cout() << "Matching test cases:\n";
10838         else {
10839             Catch::cout() << "All available test cases:\n";
10840         }
10841 
10842         auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10843         for( auto const& testCaseInfo : matchedTestCases ) {
10844             Colour::Code colour = testCaseInfo.isHidden()
10845                 ? Colour::SecondaryText
10846                 : Colour::None;
10847             Colour colourGuard( colour );
10848 
10849             Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
10850             if( config.verbosity() >= Verbosity::High ) {
10851                 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
10852                 std::string description = testCaseInfo.description;
10853                 if( description.empty() )
10854                     description = "(NO DESCRIPTION)";
10855                 Catch::cout() << Column( description ).indent(4) << std::endl;
10856             }
10857             if( !testCaseInfo.tags.empty() )
10858                 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
10859         }
10860 
10861         if( !config.hasTestFilters() )
10862             Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
10863         else
10864             Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
10865         return matchedTestCases.size();
10866     }
10867 
listTestsNamesOnly(Config const & config)10868     std::size_t listTestsNamesOnly( Config const& config ) {
10869         TestSpec testSpec = config.testSpec();
10870         std::size_t matchedTests = 0;
10871         std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10872         for( auto const& testCaseInfo : matchedTestCases ) {
10873             matchedTests++;
10874             if( startsWith( testCaseInfo.name, '#' ) )
10875                Catch::cout() << '"' << testCaseInfo.name << '"';
10876             else
10877                Catch::cout() << testCaseInfo.name;
10878             if ( config.verbosity() >= Verbosity::High )
10879                 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
10880             Catch::cout() << std::endl;
10881         }
10882         return matchedTests;
10883     }
10884 
add(std::string const & spelling)10885     void TagInfo::add( std::string const& spelling ) {
10886         ++count;
10887         spellings.insert( spelling );
10888     }
10889 
all() const10890     std::string TagInfo::all() const {
10891         size_t size = 0;
10892         for (auto const& spelling : spellings) {
10893             // Add 2 for the brackes
10894             size += spelling.size() + 2;
10895         }
10896 
10897         std::string out; out.reserve(size);
10898         for (auto const& spelling : spellings) {
10899             out += '[';
10900             out += spelling;
10901             out += ']';
10902         }
10903         return out;
10904     }
10905 
listTags(Config const & config)10906     std::size_t listTags( Config const& config ) {
10907         TestSpec testSpec = config.testSpec();
10908         if( config.hasTestFilters() )
10909             Catch::cout() << "Tags for matching test cases:\n";
10910         else {
10911             Catch::cout() << "All available tags:\n";
10912         }
10913 
10914         std::map<std::string, TagInfo> tagCounts;
10915 
10916         std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
10917         for( auto const& testCase : matchedTestCases ) {
10918             for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
10919                 std::string lcaseTagName = toLower( tagName );
10920                 auto countIt = tagCounts.find( lcaseTagName );
10921                 if( countIt == tagCounts.end() )
10922                     countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
10923                 countIt->second.add( tagName );
10924             }
10925         }
10926 
10927         for( auto const& tagCount : tagCounts ) {
10928             ReusableStringStream rss;
10929             rss << "  " << std::setw(2) << tagCount.second.count << "  ";
10930             auto str = rss.str();
10931             auto wrapper = Column( tagCount.second.all() )
10932                                                     .initialIndent( 0 )
10933                                                     .indent( str.size() )
10934                                                     .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
10935             Catch::cout() << str << wrapper << '\n';
10936         }
10937         Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
10938         return tagCounts.size();
10939     }
10940 
listReporters()10941     std::size_t listReporters() {
10942         Catch::cout() << "Available reporters:\n";
10943         IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
10944         std::size_t maxNameLen = 0;
10945         for( auto const& factoryKvp : factories )
10946             maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
10947 
10948         for( auto const& factoryKvp : factories ) {
10949             Catch::cout()
10950                     << Column( factoryKvp.first + ":" )
10951                             .indent(2)
10952                             .width( 5+maxNameLen )
10953                     +  Column( factoryKvp.second->getDescription() )
10954                             .initialIndent(0)
10955                             .indent(2)
10956                             .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
10957                     << "\n";
10958         }
10959         Catch::cout() << std::endl;
10960         return factories.size();
10961     }
10962 
list(std::shared_ptr<Config> const & config)10963     Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
10964         Option<std::size_t> listedCount;
10965         getCurrentMutableContext().setConfig( config );
10966         if( config->listTests() )
10967             listedCount = listedCount.valueOr(0) + listTests( *config );
10968         if( config->listTestNamesOnly() )
10969             listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
10970         if( config->listTags() )
10971             listedCount = listedCount.valueOr(0) + listTags( *config );
10972         if( config->listReporters() )
10973             listedCount = listedCount.valueOr(0) + listReporters();
10974         return listedCount;
10975     }
10976 
10977 } // end namespace Catch
10978 // end catch_list.cpp
10979 // start catch_matchers.cpp
10980 
10981 namespace Catch {
10982 namespace Matchers {
10983     namespace Impl {
10984 
toString() const10985         std::string MatcherUntypedBase::toString() const {
10986             if( m_cachedToString.empty() )
10987                 m_cachedToString = describe();
10988             return m_cachedToString;
10989         }
10990 
10991         MatcherUntypedBase::~MatcherUntypedBase() = default;
10992 
10993     } // namespace Impl
10994 } // namespace Matchers
10995 
10996 using namespace Matchers;
10997 using Matchers::Impl::MatcherBase;
10998 
10999 } // namespace Catch
11000 // end catch_matchers.cpp
11001 // start catch_matchers_floating.cpp
11002 
11003 // start catch_polyfills.hpp
11004 
11005 namespace Catch {
11006     bool isnan(float f);
11007     bool isnan(double d);
11008 }
11009 
11010 // end catch_polyfills.hpp
11011 // start catch_to_string.hpp
11012 
11013 #include <string>
11014 
11015 namespace Catch {
11016     template <typename T>
to_string(T const & t)11017     std::string to_string(T const& t) {
11018 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11019         return std::to_string(t);
11020 #else
11021         ReusableStringStream rss;
11022         rss << t;
11023         return rss.str();
11024 #endif
11025     }
11026 } // end namespace Catch
11027 
11028 // end catch_to_string.hpp
11029 #include <cstdlib>
11030 #include <cstdint>
11031 #include <cstring>
11032 #include <sstream>
11033 #include <iomanip>
11034 #include <limits>
11035 
11036 namespace Catch {
11037 namespace Matchers {
11038 namespace Floating {
11039 enum class FloatingPointKind : uint8_t {
11040     Float,
11041     Double
11042 };
11043 }
11044 }
11045 }
11046 
11047 namespace {
11048 
11049 template <typename T>
11050 struct Converter;
11051 
11052 template <>
11053 struct Converter<float> {
11054     static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
Converter__anon6485c3de3111::Converter11055     Converter(float f) {
11056         std::memcpy(&i, &f, sizeof(f));
11057     }
11058     int32_t i;
11059 };
11060 
11061 template <>
11062 struct Converter<double> {
11063     static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
Converter__anon6485c3de3111::Converter11064     Converter(double d) {
11065         std::memcpy(&i, &d, sizeof(d));
11066     }
11067     int64_t i;
11068 };
11069 
11070 template <typename T>
convert(T t)11071 auto convert(T t) -> Converter<T> {
11072     return Converter<T>(t);
11073 }
11074 
11075 template <typename FP>
almostEqualUlps(FP lhs,FP rhs,int maxUlpDiff)11076 bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
11077     // Comparison with NaN should always be false.
11078     // This way we can rule it out before getting into the ugly details
11079     if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11080         return false;
11081     }
11082 
11083     auto lc = convert(lhs);
11084     auto rc = convert(rhs);
11085 
11086     if ((lc.i < 0) != (rc.i < 0)) {
11087         // Potentially we can have +0 and -0
11088         return lhs == rhs;
11089     }
11090 
11091     auto ulpDiff = std::abs(lc.i - rc.i);
11092     return ulpDiff <= maxUlpDiff;
11093 }
11094 
11095 template <typename FP>
step(FP start,FP direction,int steps)11096 FP step(FP start, FP direction, int steps) {
11097     for (int i = 0; i < steps; ++i) {
11098         start = std::nextafter(start, direction);
11099     }
11100     return start;
11101 }
11102 
11103 } // end anonymous namespace
11104 
11105 namespace Catch {
11106 namespace Matchers {
11107 namespace Floating {
WithinAbsMatcher(double target,double margin)11108     WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11109         :m_target{ target }, m_margin{ margin } {
11110         CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11111             << " Margin has to be non-negative.");
11112     }
11113 
11114     // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11115     // But without the subtraction to allow for INFINITY in comparison
match(double const & matchee) const11116     bool WithinAbsMatcher::match(double const& matchee) const {
11117         return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11118     }
11119 
describe() const11120     std::string WithinAbsMatcher::describe() const {
11121         return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11122     }
11123 
WithinUlpsMatcher(double target,int ulps,FloatingPointKind baseType)11124     WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
11125         :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11126         CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
11127             << " ULPs have to be non-negative.");
11128     }
11129 
11130 #if defined(__clang__)
11131 #pragma clang diagnostic push
11132 // Clang <3.5 reports on the default branch in the switch below
11133 #pragma clang diagnostic ignored "-Wunreachable-code"
11134 #endif
11135 
match(double const & matchee) const11136     bool WithinUlpsMatcher::match(double const& matchee) const {
11137         switch (m_type) {
11138         case FloatingPointKind::Float:
11139             return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11140         case FloatingPointKind::Double:
11141             return almostEqualUlps<double>(matchee, m_target, m_ulps);
11142         default:
11143             CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11144         }
11145     }
11146 
11147 #if defined(__clang__)
11148 #pragma clang diagnostic pop
11149 #endif
11150 
describe() const11151     std::string WithinUlpsMatcher::describe() const {
11152         std::stringstream ret;
11153 
11154         ret << "is within " << m_ulps << " ULPs of " << ::Catch::Detail::stringify(m_target);
11155 
11156         if (m_type == FloatingPointKind::Float) {
11157             ret << 'f';
11158         }
11159 
11160         ret << " ([";
11161         ret << std::fixed << std::setprecision(std::numeric_limits<double>::max_digits10);
11162         if (m_type == FloatingPointKind::Double) {
11163             ret << step(m_target, static_cast<double>(-INFINITY), m_ulps)
11164                 << ", "
11165                 << step(m_target, static_cast<double>(INFINITY), m_ulps);
11166         } else {
11167             ret << step<float>(static_cast<float>(m_target), -INFINITY, m_ulps)
11168                 << ", "
11169                 << step<float>(static_cast<float>(m_target), INFINITY, m_ulps);
11170         }
11171         ret << "])";
11172 
11173         return ret.str();
11174         //return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
11175     }
11176 
11177 }// namespace Floating
11178 
WithinULP(double target,int maxUlpDiff)11179 Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
11180     return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11181 }
11182 
WithinULP(float target,int maxUlpDiff)11183 Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
11184     return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11185 }
11186 
WithinAbs(double target,double margin)11187 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11188     return Floating::WithinAbsMatcher(target, margin);
11189 }
11190 
11191 } // namespace Matchers
11192 } // namespace Catch
11193 
11194 // end catch_matchers_floating.cpp
11195 // start catch_matchers_generic.cpp
11196 
finalizeDescription(const std::string & desc)11197 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11198     if (desc.empty()) {
11199         return "matches undescribed predicate";
11200     } else {
11201         return "matches predicate: \"" + desc + '"';
11202     }
11203 }
11204 // end catch_matchers_generic.cpp
11205 // start catch_matchers_string.cpp
11206 
11207 #include <regex>
11208 
11209 namespace Catch {
11210 namespace Matchers {
11211 
11212     namespace StdString {
11213 
CasedString(std::string const & str,CaseSensitive::Choice caseSensitivity)11214         CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11215         :   m_caseSensitivity( caseSensitivity ),
11216             m_str( adjustString( str ) )
11217         {}
adjustString(std::string const & str) const11218         std::string CasedString::adjustString( std::string const& str ) const {
11219             return m_caseSensitivity == CaseSensitive::No
11220                    ? toLower( str )
11221                    : str;
11222         }
caseSensitivitySuffix() const11223         std::string CasedString::caseSensitivitySuffix() const {
11224             return m_caseSensitivity == CaseSensitive::No
11225                    ? " (case insensitive)"
11226                    : std::string();
11227         }
11228 
StringMatcherBase(std::string const & operation,CasedString const & comparator)11229         StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11230         : m_comparator( comparator ),
11231           m_operation( operation ) {
11232         }
11233 
describe() const11234         std::string StringMatcherBase::describe() const {
11235             std::string description;
11236             description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11237                                         m_comparator.caseSensitivitySuffix().size());
11238             description += m_operation;
11239             description += ": \"";
11240             description += m_comparator.m_str;
11241             description += "\"";
11242             description += m_comparator.caseSensitivitySuffix();
11243             return description;
11244         }
11245 
EqualsMatcher(CasedString const & comparator)11246         EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11247 
match(std::string const & source) const11248         bool EqualsMatcher::match( std::string const& source ) const {
11249             return m_comparator.adjustString( source ) == m_comparator.m_str;
11250         }
11251 
ContainsMatcher(CasedString const & comparator)11252         ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11253 
match(std::string const & source) const11254         bool ContainsMatcher::match( std::string const& source ) const {
11255             return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11256         }
11257 
StartsWithMatcher(CasedString const & comparator)11258         StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11259 
match(std::string const & source) const11260         bool StartsWithMatcher::match( std::string const& source ) const {
11261             return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11262         }
11263 
EndsWithMatcher(CasedString const & comparator)11264         EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11265 
match(std::string const & source) const11266         bool EndsWithMatcher::match( std::string const& source ) const {
11267             return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11268         }
11269 
RegexMatcher(std::string regex,CaseSensitive::Choice caseSensitivity)11270         RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11271 
match(std::string const & matchee) const11272         bool RegexMatcher::match(std::string const& matchee) const {
11273             auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11274             if (m_caseSensitivity == CaseSensitive::Choice::No) {
11275                 flags |= std::regex::icase;
11276             }
11277             auto reg = std::regex(m_regex, flags);
11278             return std::regex_match(matchee, reg);
11279         }
11280 
describe() const11281         std::string RegexMatcher::describe() const {
11282             return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11283         }
11284 
11285     } // namespace StdString
11286 
Equals(std::string const & str,CaseSensitive::Choice caseSensitivity)11287     StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11288         return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11289     }
Contains(std::string const & str,CaseSensitive::Choice caseSensitivity)11290     StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11291         return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11292     }
EndsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11293     StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11294         return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11295     }
StartsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11296     StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11297         return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11298     }
11299 
Matches(std::string const & regex,CaseSensitive::Choice caseSensitivity)11300     StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11301         return StdString::RegexMatcher(regex, caseSensitivity);
11302     }
11303 
11304 } // namespace Matchers
11305 } // namespace Catch
11306 // end catch_matchers_string.cpp
11307 // start catch_message.cpp
11308 
11309 // start catch_uncaught_exceptions.h
11310 
11311 namespace Catch {
11312     bool uncaught_exceptions();
11313 } // end namespace Catch
11314 
11315 // end catch_uncaught_exceptions.h
11316 #include <cassert>
11317 #include <stack>
11318 
11319 namespace Catch {
11320 
MessageInfo(StringRef const & _macroName,SourceLineInfo const & _lineInfo,ResultWas::OfType _type)11321     MessageInfo::MessageInfo(   StringRef const& _macroName,
11322                                 SourceLineInfo const& _lineInfo,
11323                                 ResultWas::OfType _type )
11324     :   macroName( _macroName ),
11325         lineInfo( _lineInfo ),
11326         type( _type ),
11327         sequence( ++globalCount )
11328     {}
11329 
operator ==(MessageInfo const & other) const11330     bool MessageInfo::operator==( MessageInfo const& other ) const {
11331         return sequence == other.sequence;
11332     }
11333 
operator <(MessageInfo const & other) const11334     bool MessageInfo::operator<( MessageInfo const& other ) const {
11335         return sequence < other.sequence;
11336     }
11337 
11338     // This may need protecting if threading support is added
11339     unsigned int MessageInfo::globalCount = 0;
11340 
11341     ////////////////////////////////////////////////////////////////////////////
11342 
MessageBuilder(StringRef const & macroName,SourceLineInfo const & lineInfo,ResultWas::OfType type)11343     Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11344                                            SourceLineInfo const& lineInfo,
11345                                            ResultWas::OfType type )
11346         :m_info(macroName, lineInfo, type) {}
11347 
11348     ////////////////////////////////////////////////////////////////////////////
11349 
ScopedMessage(MessageBuilder const & builder)11350     ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11351     : m_info( builder.m_info ), m_moved()
11352     {
11353         m_info.message = builder.m_stream.str();
11354         getResultCapture().pushScopedMessage( m_info );
11355     }
11356 
ScopedMessage(ScopedMessage && old)11357     ScopedMessage::ScopedMessage( ScopedMessage&& old )
11358     : m_info( old.m_info ), m_moved()
11359     {
11360         old.m_moved = true;
11361     }
11362 
~ScopedMessage()11363     ScopedMessage::~ScopedMessage() {
11364         if ( !uncaught_exceptions() && !m_moved ){
11365             getResultCapture().popScopedMessage(m_info);
11366         }
11367     }
11368 
Capturer(StringRef macroName,SourceLineInfo const & lineInfo,ResultWas::OfType resultType,StringRef names)11369     Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11370         auto trimmed = [&] (size_t start, size_t end) {
11371             while (names[start] == ',' || isspace(names[start])) {
11372                 ++start;
11373             }
11374             while (names[end] == ',' || isspace(names[end])) {
11375                 --end;
11376             }
11377             return names.substr(start, end - start + 1);
11378         };
11379         auto skipq = [&] (size_t start, char quote) {
11380             for (auto i = start + 1; i < names.size() ; ++i) {
11381                 if (names[i] == quote)
11382                     return i;
11383                 if (names[i] == '\\')
11384                     ++i;
11385             }
11386             CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11387         };
11388 
11389         size_t start = 0;
11390         std::stack<char> openings;
11391         for (size_t pos = 0; pos < names.size(); ++pos) {
11392             char c = names[pos];
11393             switch (c) {
11394             case '[':
11395             case '{':
11396             case '(':
11397             // It is basically impossible to disambiguate between
11398             // comparison and start of template args in this context
11399 //            case '<':
11400                 openings.push(c);
11401                 break;
11402             case ']':
11403             case '}':
11404             case ')':
11405 //           case '>':
11406                 openings.pop();
11407                 break;
11408             case '"':
11409             case '\'':
11410                 pos = skipq(pos, c);
11411                 break;
11412             case ',':
11413                 if (start != pos && openings.size() == 0) {
11414                     m_messages.emplace_back(macroName, lineInfo, resultType);
11415                     m_messages.back().message = trimmed(start, pos);
11416                     m_messages.back().message += " := ";
11417                     start = pos;
11418                 }
11419             }
11420         }
11421         assert(openings.size() == 0 && "Mismatched openings");
11422         m_messages.emplace_back(macroName, lineInfo, resultType);
11423         m_messages.back().message = trimmed(start, names.size() - 1);
11424         m_messages.back().message += " := ";
11425     }
~Capturer()11426     Capturer::~Capturer() {
11427         if ( !uncaught_exceptions() ){
11428             assert( m_captured == m_messages.size() );
11429             for( size_t i = 0; i < m_captured; ++i  )
11430                 m_resultCapture.popScopedMessage( m_messages[i] );
11431         }
11432     }
11433 
captureValue(size_t index,std::string const & value)11434     void Capturer::captureValue( size_t index, std::string const& value ) {
11435         assert( index < m_messages.size() );
11436         m_messages[index].message += value;
11437         m_resultCapture.pushScopedMessage( m_messages[index] );
11438         m_captured++;
11439     }
11440 
11441 } // end namespace Catch
11442 // end catch_message.cpp
11443 // start catch_output_redirect.cpp
11444 
11445 // start catch_output_redirect.h
11446 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11447 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11448 
11449 #include <cstdio>
11450 #include <iosfwd>
11451 #include <string>
11452 
11453 namespace Catch {
11454 
11455     class RedirectedStream {
11456         std::ostream& m_originalStream;
11457         std::ostream& m_redirectionStream;
11458         std::streambuf* m_prevBuf;
11459 
11460     public:
11461         RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11462         ~RedirectedStream();
11463     };
11464 
11465     class RedirectedStdOut {
11466         ReusableStringStream m_rss;
11467         RedirectedStream m_cout;
11468     public:
11469         RedirectedStdOut();
11470         auto str() const -> std::string;
11471     };
11472 
11473     // StdErr has two constituent streams in C++, std::cerr and std::clog
11474     // This means that we need to redirect 2 streams into 1 to keep proper
11475     // order of writes
11476     class RedirectedStdErr {
11477         ReusableStringStream m_rss;
11478         RedirectedStream m_cerr;
11479         RedirectedStream m_clog;
11480     public:
11481         RedirectedStdErr();
11482         auto str() const -> std::string;
11483     };
11484 
11485     class RedirectedStreams {
11486     public:
11487         RedirectedStreams(RedirectedStreams const&) = delete;
11488         RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11489         RedirectedStreams(RedirectedStreams&&) = delete;
11490         RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11491 
11492         RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11493         ~RedirectedStreams();
11494     private:
11495         std::string& m_redirectedCout;
11496         std::string& m_redirectedCerr;
11497         RedirectedStdOut m_redirectedStdOut;
11498         RedirectedStdErr m_redirectedStdErr;
11499     };
11500 
11501 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11502 
11503     // Windows's implementation of std::tmpfile is terrible (it tries
11504     // to create a file inside system folder, thus requiring elevated
11505     // privileges for the binary), so we have to use tmpnam(_s) and
11506     // create the file ourselves there.
11507     class TempFile {
11508     public:
11509         TempFile(TempFile const&) = delete;
11510         TempFile& operator=(TempFile const&) = delete;
11511         TempFile(TempFile&&) = delete;
11512         TempFile& operator=(TempFile&&) = delete;
11513 
11514         TempFile();
11515         ~TempFile();
11516 
11517         std::FILE* getFile();
11518         std::string getContents();
11519 
11520     private:
11521         std::FILE* m_file = nullptr;
11522     #if defined(_MSC_VER)
11523         char m_buffer[L_tmpnam] = { 0 };
11524     #endif
11525     };
11526 
11527     class OutputRedirect {
11528     public:
11529         OutputRedirect(OutputRedirect const&) = delete;
11530         OutputRedirect& operator=(OutputRedirect const&) = delete;
11531         OutputRedirect(OutputRedirect&&) = delete;
11532         OutputRedirect& operator=(OutputRedirect&&) = delete;
11533 
11534         OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
11535         ~OutputRedirect();
11536 
11537     private:
11538         int m_originalStdout = -1;
11539         int m_originalStderr = -1;
11540         TempFile m_stdoutFile;
11541         TempFile m_stderrFile;
11542         std::string& m_stdoutDest;
11543         std::string& m_stderrDest;
11544     };
11545 
11546 #endif
11547 
11548 } // end namespace Catch
11549 
11550 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11551 // end catch_output_redirect.h
11552 #include <cstdio>
11553 #include <cstring>
11554 #include <fstream>
11555 #include <sstream>
11556 #include <stdexcept>
11557 
11558 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11559     #if defined(_MSC_VER)
11560     #include <io.h>      //_dup and _dup2
11561     #define dup _dup
11562     #define dup2 _dup2
11563     #define fileno _fileno
11564     #else
11565     #include <unistd.h>  // dup and dup2
11566     #endif
11567 #endif
11568 
11569 namespace Catch {
11570 
RedirectedStream(std::ostream & originalStream,std::ostream & redirectionStream)11571     RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
11572     :   m_originalStream( originalStream ),
11573         m_redirectionStream( redirectionStream ),
11574         m_prevBuf( m_originalStream.rdbuf() )
11575     {
11576         m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
11577     }
11578 
~RedirectedStream()11579     RedirectedStream::~RedirectedStream() {
11580         m_originalStream.rdbuf( m_prevBuf );
11581     }
11582 
RedirectedStdOut()11583     RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
str() const11584     auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
11585 
RedirectedStdErr()11586     RedirectedStdErr::RedirectedStdErr()
11587     :   m_cerr( Catch::cerr(), m_rss.get() ),
11588         m_clog( Catch::clog(), m_rss.get() )
11589     {}
str() const11590     auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
11591 
RedirectedStreams(std::string & redirectedCout,std::string & redirectedCerr)11592     RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
11593     :   m_redirectedCout(redirectedCout),
11594         m_redirectedCerr(redirectedCerr)
11595     {}
11596 
~RedirectedStreams()11597     RedirectedStreams::~RedirectedStreams() {
11598         m_redirectedCout += m_redirectedStdOut.str();
11599         m_redirectedCerr += m_redirectedStdErr.str();
11600     }
11601 
11602 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11603 
11604 #if defined(_MSC_VER)
TempFile()11605     TempFile::TempFile() {
11606         if (tmpnam_s(m_buffer)) {
11607             CATCH_RUNTIME_ERROR("Could not get a temp filename");
11608         }
11609         if (fopen_s(&m_file, m_buffer, "w")) {
11610             char buffer[100];
11611             if (strerror_s(buffer, errno)) {
11612                 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
11613             }
11614             CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
11615         }
11616     }
11617 #else
TempFile()11618     TempFile::TempFile() {
11619         m_file = std::tmpfile();
11620         if (!m_file) {
11621             CATCH_RUNTIME_ERROR("Could not create a temp file.");
11622         }
11623     }
11624 
11625 #endif
11626 
~TempFile()11627     TempFile::~TempFile() {
11628          // TBD: What to do about errors here?
11629          std::fclose(m_file);
11630          // We manually create the file on Windows only, on Linux
11631          // it will be autodeleted
11632 #if defined(_MSC_VER)
11633          std::remove(m_buffer);
11634 #endif
11635     }
11636 
getFile()11637     FILE* TempFile::getFile() {
11638         return m_file;
11639     }
11640 
getContents()11641     std::string TempFile::getContents() {
11642         std::stringstream sstr;
11643         char buffer[100] = {};
11644         std::rewind(m_file);
11645         while (std::fgets(buffer, sizeof(buffer), m_file)) {
11646             sstr << buffer;
11647         }
11648         return sstr.str();
11649     }
11650 
OutputRedirect(std::string & stdout_dest,std::string & stderr_dest)11651     OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
11652         m_originalStdout(dup(1)),
11653         m_originalStderr(dup(2)),
11654         m_stdoutDest(stdout_dest),
11655         m_stderrDest(stderr_dest) {
11656         dup2(fileno(m_stdoutFile.getFile()), 1);
11657         dup2(fileno(m_stderrFile.getFile()), 2);
11658     }
11659 
~OutputRedirect()11660     OutputRedirect::~OutputRedirect() {
11661         Catch::cout() << std::flush;
11662         fflush(stdout);
11663         // Since we support overriding these streams, we flush cerr
11664         // even though std::cerr is unbuffered
11665         Catch::cerr() << std::flush;
11666         Catch::clog() << std::flush;
11667         fflush(stderr);
11668 
11669         dup2(m_originalStdout, 1);
11670         dup2(m_originalStderr, 2);
11671 
11672         m_stdoutDest += m_stdoutFile.getContents();
11673         m_stderrDest += m_stderrFile.getContents();
11674     }
11675 
11676 #endif // CATCH_CONFIG_NEW_CAPTURE
11677 
11678 } // namespace Catch
11679 
11680 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11681     #if defined(_MSC_VER)
11682     #undef dup
11683     #undef dup2
11684     #undef fileno
11685     #endif
11686 #endif
11687 // end catch_output_redirect.cpp
11688 // start catch_polyfills.cpp
11689 
11690 #include <cmath>
11691 
11692 namespace Catch {
11693 
11694 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
isnan(float f)11695     bool isnan(float f) {
11696         return std::isnan(f);
11697     }
isnan(double d)11698     bool isnan(double d) {
11699         return std::isnan(d);
11700     }
11701 #else
11702     // For now we only use this for embarcadero
11703     bool isnan(float f) {
11704         return std::_isnan(f);
11705     }
11706     bool isnan(double d) {
11707         return std::_isnan(d);
11708     }
11709 #endif
11710 
11711 } // end namespace Catch
11712 // end catch_polyfills.cpp
11713 // start catch_random_number_generator.cpp
11714 
11715 namespace Catch {
11716 
rng()11717     std::mt19937& rng() {
11718         static std::mt19937 s_rng;
11719         return s_rng;
11720     }
11721 
seedRng(IConfig const & config)11722     void seedRng( IConfig const& config ) {
11723         if( config.rngSeed() != 0 ) {
11724             std::srand( config.rngSeed() );
11725             rng().seed( config.rngSeed() );
11726         }
11727     }
11728 
rngSeed()11729     unsigned int rngSeed() {
11730         return getCurrentContext().getConfig()->rngSeed();
11731     }
11732 }
11733 // end catch_random_number_generator.cpp
11734 // start catch_registry_hub.cpp
11735 
11736 // start catch_test_case_registry_impl.h
11737 
11738 #include <vector>
11739 #include <set>
11740 #include <algorithm>
11741 #include <ios>
11742 
11743 namespace Catch {
11744 
11745     class TestCase;
11746     struct IConfig;
11747 
11748     std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
11749 
11750     bool isThrowSafe( TestCase const& testCase, IConfig const& config );
11751     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
11752 
11753     void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
11754 
11755     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
11756     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
11757 
11758     class TestRegistry : public ITestCaseRegistry {
11759     public:
11760         virtual ~TestRegistry() = default;
11761 
11762         virtual void registerTest( TestCase const& testCase );
11763 
11764         std::vector<TestCase> const& getAllTests() const override;
11765         std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
11766 
11767     private:
11768         std::vector<TestCase> m_functions;
11769         mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
11770         mutable std::vector<TestCase> m_sortedFunctions;
11771         std::size_t m_unnamedCount = 0;
11772         std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
11773     };
11774 
11775     ///////////////////////////////////////////////////////////////////////////
11776 
11777     class TestInvokerAsFunction : public ITestInvoker {
11778         void(*m_testAsFunction)();
11779     public:
11780         TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
11781 
11782         void invoke() const override;
11783     };
11784 
11785     std::string extractClassName( StringRef const& classOrQualifiedMethodName );
11786 
11787     ///////////////////////////////////////////////////////////////////////////
11788 
11789 } // end namespace Catch
11790 
11791 // end catch_test_case_registry_impl.h
11792 // start catch_reporter_registry.h
11793 
11794 #include <map>
11795 
11796 namespace Catch {
11797 
11798     class ReporterRegistry : public IReporterRegistry {
11799 
11800     public:
11801 
11802         ~ReporterRegistry() override;
11803 
11804         IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
11805 
11806         void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
11807         void registerListener( IReporterFactoryPtr const& factory );
11808 
11809         FactoryMap const& getFactories() const override;
11810         Listeners const& getListeners() const override;
11811 
11812     private:
11813         FactoryMap m_factories;
11814         Listeners m_listeners;
11815     };
11816 }
11817 
11818 // end catch_reporter_registry.h
11819 // start catch_tag_alias_registry.h
11820 
11821 // start catch_tag_alias.h
11822 
11823 #include <string>
11824 
11825 namespace Catch {
11826 
11827     struct TagAlias {
11828         TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
11829 
11830         std::string tag;
11831         SourceLineInfo lineInfo;
11832     };
11833 
11834 } // end namespace Catch
11835 
11836 // end catch_tag_alias.h
11837 #include <map>
11838 
11839 namespace Catch {
11840 
11841     class TagAliasRegistry : public ITagAliasRegistry {
11842     public:
11843         ~TagAliasRegistry() override;
11844         TagAlias const* find( std::string const& alias ) const override;
11845         std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
11846         void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
11847 
11848     private:
11849         std::map<std::string, TagAlias> m_registry;
11850     };
11851 
11852 } // end namespace Catch
11853 
11854 // end catch_tag_alias_registry.h
11855 // start catch_startup_exception_registry.h
11856 
11857 #include <vector>
11858 #include <exception>
11859 
11860 namespace Catch {
11861 
11862     class StartupExceptionRegistry {
11863     public:
11864         void add(std::exception_ptr const& exception) noexcept;
11865         std::vector<std::exception_ptr> const& getExceptions() const noexcept;
11866     private:
11867         std::vector<std::exception_ptr> m_exceptions;
11868     };
11869 
11870 } // end namespace Catch
11871 
11872 // end catch_startup_exception_registry.h
11873 // start catch_singletons.hpp
11874 
11875 namespace Catch {
11876 
11877     struct ISingleton {
11878         virtual ~ISingleton();
11879     };
11880 
11881     void addSingleton( ISingleton* singleton );
11882     void cleanupSingletons();
11883 
11884     template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
11885     class Singleton : SingletonImplT, public ISingleton {
11886 
getInternal()11887         static auto getInternal() -> Singleton* {
11888             static Singleton* s_instance = nullptr;
11889             if( !s_instance ) {
11890                 s_instance = new Singleton;
11891                 addSingleton( s_instance );
11892             }
11893             return s_instance;
11894         }
11895 
11896     public:
get()11897         static auto get() -> InterfaceT const& {
11898             return *getInternal();
11899         }
getMutable()11900         static auto getMutable() -> MutableInterfaceT& {
11901             return *getInternal();
11902         }
11903     };
11904 
11905 } // namespace Catch
11906 
11907 // end catch_singletons.hpp
11908 namespace Catch {
11909 
11910     namespace {
11911 
11912         class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
11913                             private NonCopyable {
11914 
11915         public: // IRegistryHub
11916             RegistryHub() = default;
getReporterRegistry() const11917             IReporterRegistry const& getReporterRegistry() const override {
11918                 return m_reporterRegistry;
11919             }
getTestCaseRegistry() const11920             ITestCaseRegistry const& getTestCaseRegistry() const override {
11921                 return m_testCaseRegistry;
11922             }
getExceptionTranslatorRegistry() const11923             IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
11924                 return m_exceptionTranslatorRegistry;
11925             }
getTagAliasRegistry() const11926             ITagAliasRegistry const& getTagAliasRegistry() const override {
11927                 return m_tagAliasRegistry;
11928             }
getStartupExceptionRegistry() const11929             StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
11930                 return m_exceptionRegistry;
11931             }
11932 
11933         public: // IMutableRegistryHub
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)11934             void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
11935                 m_reporterRegistry.registerReporter( name, factory );
11936             }
registerListener(IReporterFactoryPtr const & factory)11937             void registerListener( IReporterFactoryPtr const& factory ) override {
11938                 m_reporterRegistry.registerListener( factory );
11939             }
registerTest(TestCase const & testInfo)11940             void registerTest( TestCase const& testInfo ) override {
11941                 m_testCaseRegistry.registerTest( testInfo );
11942             }
registerTranslator(const IExceptionTranslator * translator)11943             void registerTranslator( const IExceptionTranslator* translator ) override {
11944                 m_exceptionTranslatorRegistry.registerTranslator( translator );
11945             }
registerTagAlias(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)11946             void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
11947                 m_tagAliasRegistry.add( alias, tag, lineInfo );
11948             }
registerStartupException()11949             void registerStartupException() noexcept override {
11950                 m_exceptionRegistry.add(std::current_exception());
11951             }
getMutableEnumValuesRegistry()11952             IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
11953                 return m_enumValuesRegistry;
11954             }
11955 
11956         private:
11957             TestRegistry m_testCaseRegistry;
11958             ReporterRegistry m_reporterRegistry;
11959             ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
11960             TagAliasRegistry m_tagAliasRegistry;
11961             StartupExceptionRegistry m_exceptionRegistry;
11962             Detail::EnumValuesRegistry m_enumValuesRegistry;
11963         };
11964     }
11965 
11966     using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
11967 
getRegistryHub()11968     IRegistryHub const& getRegistryHub() {
11969         return RegistryHubSingleton::get();
11970     }
getMutableRegistryHub()11971     IMutableRegistryHub& getMutableRegistryHub() {
11972         return RegistryHubSingleton::getMutable();
11973     }
cleanUp()11974     void cleanUp() {
11975         cleanupSingletons();
11976         cleanUpContext();
11977     }
translateActiveException()11978     std::string translateActiveException() {
11979         return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
11980     }
11981 
11982 } // end namespace Catch
11983 // end catch_registry_hub.cpp
11984 // start catch_reporter_registry.cpp
11985 
11986 namespace Catch {
11987 
11988     ReporterRegistry::~ReporterRegistry() = default;
11989 
create(std::string const & name,IConfigPtr const & config) const11990     IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
11991         auto it =  m_factories.find( name );
11992         if( it == m_factories.end() )
11993             return nullptr;
11994         return it->second->create( ReporterConfig( config ) );
11995     }
11996 
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)11997     void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
11998         m_factories.emplace(name, factory);
11999     }
registerListener(IReporterFactoryPtr const & factory)12000     void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12001         m_listeners.push_back( factory );
12002     }
12003 
getFactories() const12004     IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12005         return m_factories;
12006     }
getListeners() const12007     IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12008         return m_listeners;
12009     }
12010 
12011 }
12012 // end catch_reporter_registry.cpp
12013 // start catch_result_type.cpp
12014 
12015 namespace Catch {
12016 
isOk(ResultWas::OfType resultType)12017     bool isOk( ResultWas::OfType resultType ) {
12018         return ( resultType & ResultWas::FailureBit ) == 0;
12019     }
isJustInfo(int flags)12020     bool isJustInfo( int flags ) {
12021         return flags == ResultWas::Info;
12022     }
12023 
operator |(ResultDisposition::Flags lhs,ResultDisposition::Flags rhs)12024     ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12025         return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12026     }
12027 
shouldContinueOnFailure(int flags)12028     bool shouldContinueOnFailure( int flags )    { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
shouldSuppressFailure(int flags)12029     bool shouldSuppressFailure( int flags )      { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12030 
12031 } // end namespace Catch
12032 // end catch_result_type.cpp
12033 // start catch_run_context.cpp
12034 
12035 #include <cassert>
12036 #include <algorithm>
12037 #include <sstream>
12038 
12039 namespace Catch {
12040 
12041     namespace Generators {
12042         struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12043             GeneratorBasePtr m_generator;
12044 
GeneratorTrackerCatch::Generators::GeneratorTracker12045             GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12046             :   TrackerBase( nameAndLocation, ctx, parent )
12047             {}
12048             ~GeneratorTracker();
12049 
acquireCatch::Generators::GeneratorTracker12050             static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12051                 std::shared_ptr<GeneratorTracker> tracker;
12052 
12053                 ITracker& currentTracker = ctx.currentTracker();
12054                 if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12055                     assert( childTracker );
12056                     assert( childTracker->isGeneratorTracker() );
12057                     tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12058                 }
12059                 else {
12060                     tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
12061                     currentTracker.addChild( tracker );
12062                 }
12063 
12064                 if( !ctx.completedCycle() && !tracker->isComplete() ) {
12065                     tracker->open();
12066                 }
12067 
12068                 return *tracker;
12069             }
12070 
12071             // TrackerBase interface
isGeneratorTrackerCatch::Generators::GeneratorTracker12072             bool isGeneratorTracker() const override { return true; }
hasGeneratorCatch::Generators::GeneratorTracker12073             auto hasGenerator() const -> bool override {
12074                 return !!m_generator;
12075             }
closeCatch::Generators::GeneratorTracker12076             void close() override {
12077                 TrackerBase::close();
12078                 // Generator interface only finds out if it has another item on atual move
12079                 if (m_runState == CompletedSuccessfully && m_generator->next()) {
12080                     m_children.clear();
12081                     m_runState = Executing;
12082                 }
12083             }
12084 
12085             // IGeneratorTracker interface
getGeneratorCatch::Generators::GeneratorTracker12086             auto getGenerator() const -> GeneratorBasePtr const& override {
12087                 return m_generator;
12088             }
setGeneratorCatch::Generators::GeneratorTracker12089             void setGenerator( GeneratorBasePtr&& generator ) override {
12090                 m_generator = std::move( generator );
12091             }
12092         };
~GeneratorTracker()12093         GeneratorTracker::~GeneratorTracker() {}
12094     }
12095 
RunContext(IConfigPtr const & _config,IStreamingReporterPtr && reporter)12096     RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12097     :   m_runInfo(_config->name()),
12098         m_context(getCurrentMutableContext()),
12099         m_config(_config),
12100         m_reporter(std::move(reporter)),
12101         m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12102         m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12103     {
12104         m_context.setRunner(this);
12105         m_context.setConfig(m_config);
12106         m_context.setResultCapture(this);
12107         m_reporter->testRunStarting(m_runInfo);
12108     }
12109 
~RunContext()12110     RunContext::~RunContext() {
12111         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12112     }
12113 
testGroupStarting(std::string const & testSpec,std::size_t groupIndex,std::size_t groupsCount)12114     void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12115         m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12116     }
12117 
testGroupEnded(std::string const & testSpec,Totals const & totals,std::size_t groupIndex,std::size_t groupsCount)12118     void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12119         m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12120     }
12121 
runTest(TestCase const & testCase)12122     Totals RunContext::runTest(TestCase const& testCase) {
12123         Totals prevTotals = m_totals;
12124 
12125         std::string redirectedCout;
12126         std::string redirectedCerr;
12127 
12128         auto const& testInfo = testCase.getTestCaseInfo();
12129 
12130         m_reporter->testCaseStarting(testInfo);
12131 
12132         m_activeTestCase = &testCase;
12133 
12134         ITracker& rootTracker = m_trackerContext.startRun();
12135         assert(rootTracker.isSectionTracker());
12136         static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12137         do {
12138             m_trackerContext.startCycle();
12139             m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12140             runCurrentTest(redirectedCout, redirectedCerr);
12141         } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12142 
12143         Totals deltaTotals = m_totals.delta(prevTotals);
12144         if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12145             deltaTotals.assertions.failed++;
12146             deltaTotals.testCases.passed--;
12147             deltaTotals.testCases.failed++;
12148         }
12149         m_totals.testCases += deltaTotals.testCases;
12150         m_reporter->testCaseEnded(TestCaseStats(testInfo,
12151                                   deltaTotals,
12152                                   redirectedCout,
12153                                   redirectedCerr,
12154                                   aborting()));
12155 
12156         m_activeTestCase = nullptr;
12157         m_testCaseTracker = nullptr;
12158 
12159         return deltaTotals;
12160     }
12161 
config() const12162     IConfigPtr RunContext::config() const {
12163         return m_config;
12164     }
12165 
reporter() const12166     IStreamingReporter& RunContext::reporter() const {
12167         return *m_reporter;
12168     }
12169 
assertionEnded(AssertionResult const & result)12170     void RunContext::assertionEnded(AssertionResult const & result) {
12171         if (result.getResultType() == ResultWas::Ok) {
12172             m_totals.assertions.passed++;
12173             m_lastAssertionPassed = true;
12174         } else if (!result.isOk()) {
12175             m_lastAssertionPassed = false;
12176             if( m_activeTestCase->getTestCaseInfo().okToFail() )
12177                 m_totals.assertions.failedButOk++;
12178             else
12179                 m_totals.assertions.failed++;
12180         }
12181         else {
12182             m_lastAssertionPassed = true;
12183         }
12184 
12185         // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12186         // and should be let to clear themselves out.
12187         static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12188 
12189         if (result.getResultType() != ResultWas::Warning)
12190             m_messageScopes.clear();
12191 
12192         // Reset working state
12193         resetAssertionInfo();
12194         m_lastResult = result;
12195     }
resetAssertionInfo()12196     void RunContext::resetAssertionInfo() {
12197         m_lastAssertionInfo.macroName = StringRef();
12198         m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12199     }
12200 
sectionStarted(SectionInfo const & sectionInfo,Counts & assertions)12201     bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12202         ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12203         if (!sectionTracker.isOpen())
12204             return false;
12205         m_activeSections.push_back(&sectionTracker);
12206 
12207         m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12208 
12209         m_reporter->sectionStarting(sectionInfo);
12210 
12211         assertions = m_totals.assertions;
12212 
12213         return true;
12214     }
acquireGeneratorTracker(SourceLineInfo const & lineInfo)12215     auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12216         using namespace Generators;
12217         GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
12218         assert( tracker.isOpen() );
12219         m_lastAssertionInfo.lineInfo = lineInfo;
12220         return tracker;
12221     }
12222 
testForMissingAssertions(Counts & assertions)12223     bool RunContext::testForMissingAssertions(Counts& assertions) {
12224         if (assertions.total() != 0)
12225             return false;
12226         if (!m_config->warnAboutMissingAssertions())
12227             return false;
12228         if (m_trackerContext.currentTracker().hasChildren())
12229             return false;
12230         m_totals.assertions.failed++;
12231         assertions.failed++;
12232         return true;
12233     }
12234 
sectionEnded(SectionEndInfo const & endInfo)12235     void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12236         Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12237         bool missingAssertions = testForMissingAssertions(assertions);
12238 
12239         if (!m_activeSections.empty()) {
12240             m_activeSections.back()->close();
12241             m_activeSections.pop_back();
12242         }
12243 
12244         m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12245         m_messages.clear();
12246         m_messageScopes.clear();
12247     }
12248 
sectionEndedEarly(SectionEndInfo const & endInfo)12249     void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12250         if (m_unfinishedSections.empty())
12251             m_activeSections.back()->fail();
12252         else
12253             m_activeSections.back()->close();
12254         m_activeSections.pop_back();
12255 
12256         m_unfinishedSections.push_back(endInfo);
12257     }
12258 
12259 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)12260     void RunContext::benchmarkPreparing(std::string const& name) {
12261 		m_reporter->benchmarkPreparing(name);
12262 	}
benchmarkStarting(BenchmarkInfo const & info)12263     void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12264         m_reporter->benchmarkStarting( info );
12265     }
benchmarkEnded(BenchmarkStats<> const & stats)12266     void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12267         m_reporter->benchmarkEnded( stats );
12268     }
benchmarkFailed(std::string const & error)12269 	void RunContext::benchmarkFailed(std::string const & error) {
12270 		m_reporter->benchmarkFailed(error);
12271 	}
12272 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12273 
pushScopedMessage(MessageInfo const & message)12274     void RunContext::pushScopedMessage(MessageInfo const & message) {
12275         m_messages.push_back(message);
12276     }
12277 
popScopedMessage(MessageInfo const & message)12278     void RunContext::popScopedMessage(MessageInfo const & message) {
12279         m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12280     }
12281 
emplaceUnscopedMessage(MessageBuilder const & builder)12282     void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12283         m_messageScopes.emplace_back( builder );
12284     }
12285 
getCurrentTestName() const12286     std::string RunContext::getCurrentTestName() const {
12287         return m_activeTestCase
12288             ? m_activeTestCase->getTestCaseInfo().name
12289             : std::string();
12290     }
12291 
getLastResult() const12292     const AssertionResult * RunContext::getLastResult() const {
12293         return &(*m_lastResult);
12294     }
12295 
exceptionEarlyReported()12296     void RunContext::exceptionEarlyReported() {
12297         m_shouldReportUnexpected = false;
12298     }
12299 
handleFatalErrorCondition(StringRef message)12300     void RunContext::handleFatalErrorCondition( StringRef message ) {
12301         // First notify reporter that bad things happened
12302         m_reporter->fatalErrorEncountered(message);
12303 
12304         // Don't rebuild the result -- the stringification itself can cause more fatal errors
12305         // Instead, fake a result data.
12306         AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12307         tempResult.message = message;
12308         AssertionResult result(m_lastAssertionInfo, tempResult);
12309 
12310         assertionEnded(result);
12311 
12312         handleUnfinishedSections();
12313 
12314         // Recreate section for test case (as we will lose the one that was in scope)
12315         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12316         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12317 
12318         Counts assertions;
12319         assertions.failed = 1;
12320         SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12321         m_reporter->sectionEnded(testCaseSectionStats);
12322 
12323         auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12324 
12325         Totals deltaTotals;
12326         deltaTotals.testCases.failed = 1;
12327         deltaTotals.assertions.failed = 1;
12328         m_reporter->testCaseEnded(TestCaseStats(testInfo,
12329                                   deltaTotals,
12330                                   std::string(),
12331                                   std::string(),
12332                                   false));
12333         m_totals.testCases.failed++;
12334         testGroupEnded(std::string(), m_totals, 1, 1);
12335         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12336     }
12337 
lastAssertionPassed()12338     bool RunContext::lastAssertionPassed() {
12339          return m_lastAssertionPassed;
12340     }
12341 
assertionPassed()12342     void RunContext::assertionPassed() {
12343         m_lastAssertionPassed = true;
12344         ++m_totals.assertions.passed;
12345         resetAssertionInfo();
12346         m_messageScopes.clear();
12347     }
12348 
aborting() const12349     bool RunContext::aborting() const {
12350         return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12351     }
12352 
runCurrentTest(std::string & redirectedCout,std::string & redirectedCerr)12353     void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12354         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12355         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12356         m_reporter->sectionStarting(testCaseSection);
12357         Counts prevAssertions = m_totals.assertions;
12358         double duration = 0;
12359         m_shouldReportUnexpected = true;
12360         m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12361 
12362         seedRng(*m_config);
12363 
12364         Timer timer;
12365         CATCH_TRY {
12366             if (m_reporter->getPreferences().shouldRedirectStdOut) {
12367 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12368                 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12369 
12370                 timer.start();
12371                 invokeActiveTestCase();
12372 #else
12373                 OutputRedirect r(redirectedCout, redirectedCerr);
12374                 timer.start();
12375                 invokeActiveTestCase();
12376 #endif
12377             } else {
12378                 timer.start();
12379                 invokeActiveTestCase();
12380             }
12381             duration = timer.getElapsedSeconds();
12382         } CATCH_CATCH_ANON (TestFailureException&) {
12383             // This just means the test was aborted due to failure
12384         } CATCH_CATCH_ALL {
12385             // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
12386             // are reported without translation at the point of origin.
12387             if( m_shouldReportUnexpected ) {
12388                 AssertionReaction dummyReaction;
12389                 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
12390             }
12391         }
12392         Counts assertions = m_totals.assertions - prevAssertions;
12393         bool missingAssertions = testForMissingAssertions(assertions);
12394 
12395         m_testCaseTracker->close();
12396         handleUnfinishedSections();
12397         m_messages.clear();
12398         m_messageScopes.clear();
12399 
12400         SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12401         m_reporter->sectionEnded(testCaseSectionStats);
12402     }
12403 
invokeActiveTestCase()12404     void RunContext::invokeActiveTestCase() {
12405         FatalConditionHandler fatalConditionHandler; // Handle signals
12406         m_activeTestCase->invoke();
12407         fatalConditionHandler.reset();
12408     }
12409 
handleUnfinishedSections()12410     void RunContext::handleUnfinishedSections() {
12411         // If sections ended prematurely due to an exception we stored their
12412         // infos here so we can tear them down outside the unwind process.
12413         for (auto it = m_unfinishedSections.rbegin(),
12414              itEnd = m_unfinishedSections.rend();
12415              it != itEnd;
12416              ++it)
12417             sectionEnded(*it);
12418         m_unfinishedSections.clear();
12419     }
12420 
handleExpr(AssertionInfo const & info,ITransientExpression const & expr,AssertionReaction & reaction)12421     void RunContext::handleExpr(
12422         AssertionInfo const& info,
12423         ITransientExpression const& expr,
12424         AssertionReaction& reaction
12425     ) {
12426         m_reporter->assertionStarting( info );
12427 
12428         bool negated = isFalseTest( info.resultDisposition );
12429         bool result = expr.getResult() != negated;
12430 
12431         if( result ) {
12432             if (!m_includeSuccessfulResults) {
12433                 assertionPassed();
12434             }
12435             else {
12436                 reportExpr(info, ResultWas::Ok, &expr, negated);
12437             }
12438         }
12439         else {
12440             reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
12441             populateReaction( reaction );
12442         }
12443     }
reportExpr(AssertionInfo const & info,ResultWas::OfType resultType,ITransientExpression const * expr,bool negated)12444     void RunContext::reportExpr(
12445             AssertionInfo const &info,
12446             ResultWas::OfType resultType,
12447             ITransientExpression const *expr,
12448             bool negated ) {
12449 
12450         m_lastAssertionInfo = info;
12451         AssertionResultData data( resultType, LazyExpression( negated ) );
12452 
12453         AssertionResult assertionResult{ info, data };
12454         assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
12455 
12456         assertionEnded( assertionResult );
12457     }
12458 
handleMessage(AssertionInfo const & info,ResultWas::OfType resultType,StringRef const & message,AssertionReaction & reaction)12459     void RunContext::handleMessage(
12460             AssertionInfo const& info,
12461             ResultWas::OfType resultType,
12462             StringRef const& message,
12463             AssertionReaction& reaction
12464     ) {
12465         m_reporter->assertionStarting( info );
12466 
12467         m_lastAssertionInfo = info;
12468 
12469         AssertionResultData data( resultType, LazyExpression( false ) );
12470         data.message = message;
12471         AssertionResult assertionResult{ m_lastAssertionInfo, data };
12472         assertionEnded( assertionResult );
12473         if( !assertionResult.isOk() )
12474             populateReaction( reaction );
12475     }
handleUnexpectedExceptionNotThrown(AssertionInfo const & info,AssertionReaction & reaction)12476     void RunContext::handleUnexpectedExceptionNotThrown(
12477             AssertionInfo const& info,
12478             AssertionReaction& reaction
12479     ) {
12480         handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
12481     }
12482 
handleUnexpectedInflightException(AssertionInfo const & info,std::string const & message,AssertionReaction & reaction)12483     void RunContext::handleUnexpectedInflightException(
12484             AssertionInfo const& info,
12485             std::string const& message,
12486             AssertionReaction& reaction
12487     ) {
12488         m_lastAssertionInfo = info;
12489 
12490         AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
12491         data.message = message;
12492         AssertionResult assertionResult{ info, data };
12493         assertionEnded( assertionResult );
12494         populateReaction( reaction );
12495     }
12496 
populateReaction(AssertionReaction & reaction)12497     void RunContext::populateReaction( AssertionReaction& reaction ) {
12498         reaction.shouldDebugBreak = m_config->shouldDebugBreak();
12499         reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
12500     }
12501 
handleIncomplete(AssertionInfo const & info)12502     void RunContext::handleIncomplete(
12503             AssertionInfo const& info
12504     ) {
12505         m_lastAssertionInfo = info;
12506 
12507         AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
12508         data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
12509         AssertionResult assertionResult{ info, data };
12510         assertionEnded( assertionResult );
12511     }
handleNonExpr(AssertionInfo const & info,ResultWas::OfType resultType,AssertionReaction & reaction)12512     void RunContext::handleNonExpr(
12513             AssertionInfo const &info,
12514             ResultWas::OfType resultType,
12515             AssertionReaction &reaction
12516     ) {
12517         m_lastAssertionInfo = info;
12518 
12519         AssertionResultData data( resultType, LazyExpression( false ) );
12520         AssertionResult assertionResult{ info, data };
12521         assertionEnded( assertionResult );
12522 
12523         if( !assertionResult.isOk() )
12524             populateReaction( reaction );
12525     }
12526 
getResultCapture()12527     IResultCapture& getResultCapture() {
12528         if (auto* capture = getCurrentContext().getResultCapture())
12529             return *capture;
12530         else
12531             CATCH_INTERNAL_ERROR("No result capture instance");
12532     }
12533 }
12534 // end catch_run_context.cpp
12535 // start catch_section.cpp
12536 
12537 namespace Catch {
12538 
Section(SectionInfo const & info)12539     Section::Section( SectionInfo const& info )
12540     :   m_info( info ),
12541         m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
12542     {
12543         m_timer.start();
12544     }
12545 
~Section()12546     Section::~Section() {
12547         if( m_sectionIncluded ) {
12548             SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
12549             if( uncaught_exceptions() )
12550                 getResultCapture().sectionEndedEarly( endInfo );
12551             else
12552                 getResultCapture().sectionEnded( endInfo );
12553         }
12554     }
12555 
12556     // This indicates whether the section should be executed or not
operator bool() const12557     Section::operator bool() const {
12558         return m_sectionIncluded;
12559     }
12560 
12561 } // end namespace Catch
12562 // end catch_section.cpp
12563 // start catch_section_info.cpp
12564 
12565 namespace Catch {
12566 
SectionInfo(SourceLineInfo const & _lineInfo,std::string const & _name)12567     SectionInfo::SectionInfo
12568         (   SourceLineInfo const& _lineInfo,
12569             std::string const& _name )
12570     :   name( _name ),
12571         lineInfo( _lineInfo )
12572     {}
12573 
12574 } // end namespace Catch
12575 // end catch_section_info.cpp
12576 // start catch_session.cpp
12577 
12578 // start catch_session.h
12579 
12580 #include <memory>
12581 
12582 namespace Catch {
12583 
12584     class Session : NonCopyable {
12585     public:
12586 
12587         Session();
12588         ~Session() override;
12589 
12590         void showHelp() const;
12591         void libIdentify();
12592 
12593         int applyCommandLine( int argc, char const * const * argv );
12594     #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
12595         int applyCommandLine( int argc, wchar_t const * const * argv );
12596     #endif
12597 
12598         void useConfigData( ConfigData const& configData );
12599 
12600         template<typename CharT>
run(int argc,CharT const * const argv[])12601         int run(int argc, CharT const * const argv[]) {
12602             if (m_startupExceptions)
12603                 return 1;
12604             int returnCode = applyCommandLine(argc, argv);
12605             if (returnCode == 0)
12606                 returnCode = run();
12607             return returnCode;
12608         }
12609 
12610         int run();
12611 
12612         clara::Parser const& cli() const;
12613         void cli( clara::Parser const& newParser );
12614         ConfigData& configData();
12615         Config& config();
12616     private:
12617         int runInternal();
12618 
12619         clara::Parser m_cli;
12620         ConfigData m_configData;
12621         std::shared_ptr<Config> m_config;
12622         bool m_startupExceptions = false;
12623     };
12624 
12625 } // end namespace Catch
12626 
12627 // end catch_session.h
12628 // start catch_version.h
12629 
12630 #include <iosfwd>
12631 
12632 namespace Catch {
12633 
12634     // Versioning information
12635     struct Version {
12636         Version( Version const& ) = delete;
12637         Version& operator=( Version const& ) = delete;
12638         Version(    unsigned int _majorVersion,
12639                     unsigned int _minorVersion,
12640                     unsigned int _patchNumber,
12641                     char const * const _branchName,
12642                     unsigned int _buildNumber );
12643 
12644         unsigned int const majorVersion;
12645         unsigned int const minorVersion;
12646         unsigned int const patchNumber;
12647 
12648         // buildNumber is only used if branchName is not null
12649         char const * const branchName;
12650         unsigned int const buildNumber;
12651 
12652         friend std::ostream& operator << ( std::ostream& os, Version const& version );
12653     };
12654 
12655     Version const& libraryVersion();
12656 }
12657 
12658 // end catch_version.h
12659 #include <cstdlib>
12660 #include <iomanip>
12661 #include <set>
12662 #include <iterator>
12663 
12664 namespace Catch {
12665 
12666     namespace {
12667         const int MaxExitCode = 255;
12668 
createReporter(std::string const & reporterName,IConfigPtr const & config)12669         IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
12670             auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
12671             CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
12672 
12673             return reporter;
12674         }
12675 
makeReporter(std::shared_ptr<Config> const & config)12676         IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
12677             if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
12678                 return createReporter(config->getReporterName(), config);
12679             }
12680 
12681             // On older platforms, returning std::unique_ptr<ListeningReporter>
12682             // when the return type is std::unique_ptr<IStreamingReporter>
12683             // doesn't compile without a std::move call. However, this causes
12684             // a warning on newer platforms. Thus, we have to work around
12685             // it a bit and downcast the pointer manually.
12686             auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
12687             auto& multi = static_cast<ListeningReporter&>(*ret);
12688             auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
12689             for (auto const& listener : listeners) {
12690                 multi.addListener(listener->create(Catch::ReporterConfig(config)));
12691             }
12692             multi.addReporter(createReporter(config->getReporterName(), config));
12693             return ret;
12694         }
12695 
12696         class TestGroup {
12697         public:
TestGroup(std::shared_ptr<Config> const & config)12698             explicit TestGroup(std::shared_ptr<Config> const& config)
12699             : m_config{config}
12700             , m_context{config, makeReporter(config)}
12701             {
12702                 auto const& allTestCases = getAllTestCasesSorted(*m_config);
12703                 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
12704 
12705                 if (m_matches.empty()) {
12706                     for (auto const& test : allTestCases)
12707                         if (!test.isHidden())
12708                             m_tests.emplace(&test);
12709                 } else {
12710                     for (auto const& match : m_matches)
12711                         m_tests.insert(match.tests.begin(), match.tests.end());
12712                 }
12713             }
12714 
execute()12715             Totals execute() {
12716                 Totals totals;
12717                 m_context.testGroupStarting(m_config->name(), 1, 1);
12718                 for (auto const& testCase : m_tests) {
12719                     if (!m_context.aborting())
12720                         totals += m_context.runTest(*testCase);
12721                     else
12722                         m_context.reporter().skipTest(*testCase);
12723                 }
12724 
12725                 for (auto const& match : m_matches) {
12726                     if (match.tests.empty()) {
12727                         m_context.reporter().noMatchingTestCases(match.name);
12728                         totals.error = -1;
12729                     }
12730                 }
12731                 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
12732                 return totals;
12733             }
12734 
12735         private:
12736             using Tests = std::set<TestCase const*>;
12737 
12738             std::shared_ptr<Config> m_config;
12739             RunContext m_context;
12740             Tests m_tests;
12741             TestSpec::Matches m_matches;
12742         };
12743 
applyFilenamesAsTags(Catch::IConfig const & config)12744         void applyFilenamesAsTags(Catch::IConfig const& config) {
12745             auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
12746             for (auto& testCase : tests) {
12747                 auto tags = testCase.tags;
12748 
12749                 std::string filename = testCase.lineInfo.file;
12750                 auto lastSlash = filename.find_last_of("\\/");
12751                 if (lastSlash != std::string::npos) {
12752                     filename.erase(0, lastSlash);
12753                     filename[0] = '#';
12754                 }
12755 
12756                 auto lastDot = filename.find_last_of('.');
12757                 if (lastDot != std::string::npos) {
12758                     filename.erase(lastDot);
12759                 }
12760 
12761                 tags.push_back(std::move(filename));
12762                 setTags(testCase, tags);
12763             }
12764         }
12765 
12766     } // anon namespace
12767 
Session()12768     Session::Session() {
12769         static bool alreadyInstantiated = false;
12770         if( alreadyInstantiated ) {
12771             CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
12772             CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
12773         }
12774 
12775         // There cannot be exceptions at startup in no-exception mode.
12776 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12777         const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
12778         if ( !exceptions.empty() ) {
12779             config();
12780             getCurrentMutableContext().setConfig(m_config);
12781 
12782             m_startupExceptions = true;
12783             Colour colourGuard( Colour::Red );
12784             Catch::cerr() << "Errors occurred during startup!" << '\n';
12785             // iterate over all exceptions and notify user
12786             for ( const auto& ex_ptr : exceptions ) {
12787                 try {
12788                     std::rethrow_exception(ex_ptr);
12789                 } catch ( std::exception const& ex ) {
12790                     Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
12791                 }
12792             }
12793         }
12794 #endif
12795 
12796         alreadyInstantiated = true;
12797         m_cli = makeCommandLineParser( m_configData );
12798     }
~Session()12799     Session::~Session() {
12800         Catch::cleanUp();
12801     }
12802 
showHelp() const12803     void Session::showHelp() const {
12804         Catch::cout()
12805                 << "\nCatch v" << libraryVersion() << "\n"
12806                 << m_cli << std::endl
12807                 << "For more detailed usage please see the project docs\n" << std::endl;
12808     }
libIdentify()12809     void Session::libIdentify() {
12810         Catch::cout()
12811                 << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
12812                 << std::left << std::setw(16) << "category: " << "testframework\n"
12813                 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
12814                 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
12815     }
12816 
applyCommandLine(int argc,char const * const * argv)12817     int Session::applyCommandLine( int argc, char const * const * argv ) {
12818         if( m_startupExceptions )
12819             return 1;
12820 
12821         auto result = m_cli.parse( clara::Args( argc, argv ) );
12822         if( !result ) {
12823             config();
12824             getCurrentMutableContext().setConfig(m_config);
12825             Catch::cerr()
12826                 << Colour( Colour::Red )
12827                 << "\nError(s) in input:\n"
12828                 << Column( result.errorMessage() ).indent( 2 )
12829                 << "\n\n";
12830             Catch::cerr() << "Run with -? for usage\n" << std::endl;
12831             return MaxExitCode;
12832         }
12833 
12834         if( m_configData.showHelp )
12835             showHelp();
12836         if( m_configData.libIdentify )
12837             libIdentify();
12838         m_config.reset();
12839         return 0;
12840     }
12841 
12842 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
applyCommandLine(int argc,wchar_t const * const * argv)12843     int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
12844 
12845         char **utf8Argv = new char *[ argc ];
12846 
12847         for ( int i = 0; i < argc; ++i ) {
12848             int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
12849 
12850             utf8Argv[ i ] = new char[ bufSize ];
12851 
12852             WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
12853         }
12854 
12855         int returnCode = applyCommandLine( argc, utf8Argv );
12856 
12857         for ( int i = 0; i < argc; ++i )
12858             delete [] utf8Argv[ i ];
12859 
12860         delete [] utf8Argv;
12861 
12862         return returnCode;
12863     }
12864 #endif
12865 
useConfigData(ConfigData const & configData)12866     void Session::useConfigData( ConfigData const& configData ) {
12867         m_configData = configData;
12868         m_config.reset();
12869     }
12870 
run()12871     int Session::run() {
12872         if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
12873             Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
12874             static_cast<void>(std::getchar());
12875         }
12876         int exitCode = runInternal();
12877         if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
12878             Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
12879             static_cast<void>(std::getchar());
12880         }
12881         return exitCode;
12882     }
12883 
cli() const12884     clara::Parser const& Session::cli() const {
12885         return m_cli;
12886     }
cli(clara::Parser const & newParser)12887     void Session::cli( clara::Parser const& newParser ) {
12888         m_cli = newParser;
12889     }
configData()12890     ConfigData& Session::configData() {
12891         return m_configData;
12892     }
config()12893     Config& Session::config() {
12894         if( !m_config )
12895             m_config = std::make_shared<Config>( m_configData );
12896         return *m_config;
12897     }
12898 
runInternal()12899     int Session::runInternal() {
12900         if( m_startupExceptions )
12901             return 1;
12902 
12903         if (m_configData.showHelp || m_configData.libIdentify) {
12904             return 0;
12905         }
12906 
12907         CATCH_TRY {
12908             config(); // Force config to be constructed
12909 
12910             seedRng( *m_config );
12911 
12912             if( m_configData.filenamesAsTags )
12913                 applyFilenamesAsTags( *m_config );
12914 
12915             // Handle list request
12916             if( Option<std::size_t> listed = list( m_config ) )
12917                 return static_cast<int>( *listed );
12918 
12919             TestGroup tests { m_config };
12920             auto const totals = tests.execute();
12921 
12922             if( m_config->warnAboutNoTests() && totals.error == -1 )
12923                 return 2;
12924 
12925             // Note that on unices only the lower 8 bits are usually used, clamping
12926             // the return value to 255 prevents false negative when some multiple
12927             // of 256 tests has failed
12928             return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
12929         }
12930 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12931         catch( std::exception& ex ) {
12932             Catch::cerr() << ex.what() << std::endl;
12933             return MaxExitCode;
12934         }
12935 #endif
12936     }
12937 
12938 } // end namespace Catch
12939 // end catch_session.cpp
12940 // start catch_singletons.cpp
12941 
12942 #include <vector>
12943 
12944 namespace Catch {
12945 
12946     namespace {
getSingletons()12947         static auto getSingletons() -> std::vector<ISingleton*>*& {
12948             static std::vector<ISingleton*>* g_singletons = nullptr;
12949             if( !g_singletons )
12950                 g_singletons = new std::vector<ISingleton*>();
12951             return g_singletons;
12952         }
12953     }
12954 
~ISingleton()12955     ISingleton::~ISingleton() {}
12956 
addSingleton(ISingleton * singleton)12957     void addSingleton(ISingleton* singleton ) {
12958         getSingletons()->push_back( singleton );
12959     }
cleanupSingletons()12960     void cleanupSingletons() {
12961         auto& singletons = getSingletons();
12962         for( auto singleton : *singletons )
12963             delete singleton;
12964         delete singletons;
12965         singletons = nullptr;
12966     }
12967 
12968 } // namespace Catch
12969 // end catch_singletons.cpp
12970 // start catch_startup_exception_registry.cpp
12971 
12972 namespace Catch {
add(std::exception_ptr const & exception)12973 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
12974         CATCH_TRY {
12975             m_exceptions.push_back(exception);
12976         } CATCH_CATCH_ALL {
12977             // If we run out of memory during start-up there's really not a lot more we can do about it
12978             std::terminate();
12979         }
12980     }
12981 
getExceptions() const12982     std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
12983         return m_exceptions;
12984     }
12985 
12986 } // end namespace Catch
12987 // end catch_startup_exception_registry.cpp
12988 // start catch_stream.cpp
12989 
12990 #include <cstdio>
12991 #include <iostream>
12992 #include <fstream>
12993 #include <sstream>
12994 #include <vector>
12995 #include <memory>
12996 
12997 namespace Catch {
12998 
12999     Catch::IStream::~IStream() = default;
13000 
13001     namespace Detail { namespace {
13002         template<typename WriterF, std::size_t bufferSize=256>
13003         class StreamBufImpl : public std::streambuf {
13004             char data[bufferSize];
13005             WriterF m_writer;
13006 
13007         public:
StreamBufImpl()13008             StreamBufImpl() {
13009                 setp( data, data + sizeof(data) );
13010             }
13011 
~StreamBufImpl()13012             ~StreamBufImpl() noexcept {
13013                 StreamBufImpl::sync();
13014             }
13015 
13016         private:
overflow(int c)13017             int overflow( int c ) override {
13018                 sync();
13019 
13020                 if( c != EOF ) {
13021                     if( pbase() == epptr() )
13022                         m_writer( std::string( 1, static_cast<char>( c ) ) );
13023                     else
13024                         sputc( static_cast<char>( c ) );
13025                 }
13026                 return 0;
13027             }
13028 
sync()13029             int sync() override {
13030                 if( pbase() != pptr() ) {
13031                     m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13032                     setp( pbase(), epptr() );
13033                 }
13034                 return 0;
13035             }
13036         };
13037 
13038         ///////////////////////////////////////////////////////////////////////////
13039 
13040         struct OutputDebugWriter {
13041 
operator ()Catch::Detail::__anon6485c3de3711::OutputDebugWriter13042             void operator()( std::string const&str ) {
13043                 writeToDebugConsole( str );
13044             }
13045         };
13046 
13047         ///////////////////////////////////////////////////////////////////////////
13048 
13049         class FileStream : public IStream {
13050             mutable std::ofstream m_ofs;
13051         public:
FileStream(StringRef filename)13052             FileStream( StringRef filename ) {
13053                 m_ofs.open( filename.c_str() );
13054                 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13055             }
13056             ~FileStream() override = default;
13057         public: // IStream
stream() const13058             std::ostream& stream() const override {
13059                 return m_ofs;
13060             }
13061         };
13062 
13063         ///////////////////////////////////////////////////////////////////////////
13064 
13065         class CoutStream : public IStream {
13066             mutable std::ostream m_os;
13067         public:
13068             // Store the streambuf from cout up-front because
13069             // cout may get redirected when running tests
CoutStream()13070             CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13071             ~CoutStream() override = default;
13072 
13073         public: // IStream
stream() const13074             std::ostream& stream() const override { return m_os; }
13075         };
13076 
13077         ///////////////////////////////////////////////////////////////////////////
13078 
13079         class DebugOutStream : public IStream {
13080             std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13081             mutable std::ostream m_os;
13082         public:
DebugOutStream()13083             DebugOutStream()
13084             :   m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13085                 m_os( m_streamBuf.get() )
13086             {}
13087 
13088             ~DebugOutStream() override = default;
13089 
13090         public: // IStream
stream() const13091             std::ostream& stream() const override { return m_os; }
13092         };
13093 
13094     }} // namespace anon::detail
13095 
13096     ///////////////////////////////////////////////////////////////////////////
13097 
makeStream(StringRef const & filename)13098     auto makeStream( StringRef const &filename ) -> IStream const* {
13099         if( filename.empty() )
13100             return new Detail::CoutStream();
13101         else if( filename[0] == '%' ) {
13102             if( filename == "%debug" )
13103                 return new Detail::DebugOutStream();
13104             else
13105                 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13106         }
13107         else
13108             return new Detail::FileStream( filename );
13109     }
13110 
13111     // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13112     struct StringStreams {
13113         std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13114         std::vector<std::size_t> m_unused;
13115         std::ostringstream m_referenceStream; // Used for copy state/ flags from
13116 
addCatch::StringStreams13117         auto add() -> std::size_t {
13118             if( m_unused.empty() ) {
13119                 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13120                 return m_streams.size()-1;
13121             }
13122             else {
13123                 auto index = m_unused.back();
13124                 m_unused.pop_back();
13125                 return index;
13126             }
13127         }
13128 
releaseCatch::StringStreams13129         void release( std::size_t index ) {
13130             m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13131             m_unused.push_back(index);
13132         }
13133     };
13134 
ReusableStringStream()13135     ReusableStringStream::ReusableStringStream()
13136     :   m_index( Singleton<StringStreams>::getMutable().add() ),
13137         m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13138     {}
13139 
~ReusableStringStream()13140     ReusableStringStream::~ReusableStringStream() {
13141         static_cast<std::ostringstream*>( m_oss )->str("");
13142         m_oss->clear();
13143         Singleton<StringStreams>::getMutable().release( m_index );
13144     }
13145 
str() const13146     auto ReusableStringStream::str() const -> std::string {
13147         return static_cast<std::ostringstream*>( m_oss )->str();
13148     }
13149 
13150     ///////////////////////////////////////////////////////////////////////////
13151 
13152 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
cout()13153     std::ostream& cout() { return std::cout; }
cerr()13154     std::ostream& cerr() { return std::cerr; }
clog()13155     std::ostream& clog() { return std::clog; }
13156 #endif
13157 }
13158 // end catch_stream.cpp
13159 // start catch_string_manip.cpp
13160 
13161 #include <algorithm>
13162 #include <ostream>
13163 #include <cstring>
13164 #include <cctype>
13165 #include <vector>
13166 
13167 namespace Catch {
13168 
13169     namespace {
toLowerCh(char c)13170         char toLowerCh(char c) {
13171             return static_cast<char>( std::tolower( c ) );
13172         }
13173     }
13174 
startsWith(std::string const & s,std::string const & prefix)13175     bool startsWith( std::string const& s, std::string const& prefix ) {
13176         return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13177     }
startsWith(std::string const & s,char prefix)13178     bool startsWith( std::string const& s, char prefix ) {
13179         return !s.empty() && s[0] == prefix;
13180     }
endsWith(std::string const & s,std::string const & suffix)13181     bool endsWith( std::string const& s, std::string const& suffix ) {
13182         return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13183     }
endsWith(std::string const & s,char suffix)13184     bool endsWith( std::string const& s, char suffix ) {
13185         return !s.empty() && s[s.size()-1] == suffix;
13186     }
contains(std::string const & s,std::string const & infix)13187     bool contains( std::string const& s, std::string const& infix ) {
13188         return s.find( infix ) != std::string::npos;
13189     }
toLowerInPlace(std::string & s)13190     void toLowerInPlace( std::string& s ) {
13191         std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13192     }
toLower(std::string const & s)13193     std::string toLower( std::string const& s ) {
13194         std::string lc = s;
13195         toLowerInPlace( lc );
13196         return lc;
13197     }
trim(std::string const & str)13198     std::string trim( std::string const& str ) {
13199         static char const* whitespaceChars = "\n\r\t ";
13200         std::string::size_type start = str.find_first_not_of( whitespaceChars );
13201         std::string::size_type end = str.find_last_not_of( whitespaceChars );
13202 
13203         return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13204     }
13205 
replaceInPlace(std::string & str,std::string const & replaceThis,std::string const & withThis)13206     bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13207         bool replaced = false;
13208         std::size_t i = str.find( replaceThis );
13209         while( i != std::string::npos ) {
13210             replaced = true;
13211             str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13212             if( i < str.size()-withThis.size() )
13213                 i = str.find( replaceThis, i+withThis.size() );
13214             else
13215                 i = std::string::npos;
13216         }
13217         return replaced;
13218     }
13219 
splitStringRef(StringRef str,char delimiter)13220     std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13221         std::vector<StringRef> subStrings;
13222         std::size_t start = 0;
13223         for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13224             if( str[pos] == delimiter ) {
13225                 if( pos - start > 1 )
13226                     subStrings.push_back( str.substr( start, pos-start ) );
13227                 start = pos+1;
13228             }
13229         }
13230         if( start < str.size() )
13231             subStrings.push_back( str.substr( start, str.size()-start ) );
13232         return subStrings;
13233     }
13234 
pluralise(std::size_t count,std::string const & label)13235     pluralise::pluralise( std::size_t count, std::string const& label )
13236     :   m_count( count ),
13237         m_label( label )
13238     {}
13239 
operator <<(std::ostream & os,pluralise const & pluraliser)13240     std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13241         os << pluraliser.m_count << ' ' << pluraliser.m_label;
13242         if( pluraliser.m_count != 1 )
13243             os << 's';
13244         return os;
13245     }
13246 
13247 }
13248 // end catch_string_manip.cpp
13249 // start catch_stringref.cpp
13250 
13251 #if defined(__clang__)
13252 #    pragma clang diagnostic push
13253 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
13254 #endif
13255 
13256 #include <ostream>
13257 #include <cstring>
13258 #include <cstdint>
13259 
13260 namespace {
13261     const uint32_t byte_2_lead = 0xC0;
13262     const uint32_t byte_3_lead = 0xE0;
13263     const uint32_t byte_4_lead = 0xF0;
13264 }
13265 
13266 namespace Catch {
StringRef(char const * rawChars)13267     StringRef::StringRef( char const* rawChars ) noexcept
13268     : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13269     {}
13270 
operator std::string() const13271     StringRef::operator std::string() const {
13272         return std::string( m_start, m_size );
13273     }
13274 
swap(StringRef & other)13275     void StringRef::swap( StringRef& other ) noexcept {
13276         std::swap( m_start, other.m_start );
13277         std::swap( m_size, other.m_size );
13278         std::swap( m_data, other.m_data );
13279     }
13280 
c_str() const13281     auto StringRef::c_str() const -> char const* {
13282         if( !isSubstring() )
13283             return m_start;
13284 
13285         const_cast<StringRef *>( this )->takeOwnership();
13286         return m_data;
13287     }
currentData() const13288     auto StringRef::currentData() const noexcept -> char const* {
13289         return m_start;
13290     }
13291 
isOwned() const13292     auto StringRef::isOwned() const noexcept -> bool {
13293         return m_data != nullptr;
13294     }
isSubstring() const13295     auto StringRef::isSubstring() const noexcept -> bool {
13296         return m_start[m_size] != '\0';
13297     }
13298 
takeOwnership()13299     void StringRef::takeOwnership() {
13300         if( !isOwned() ) {
13301             m_data = new char[m_size+1];
13302             memcpy( m_data, m_start, m_size );
13303             m_data[m_size] = '\0';
13304         }
13305     }
substr(size_type start,size_type size) const13306     auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13307         if( start < m_size )
13308             return StringRef( m_start+start, size );
13309         else
13310             return StringRef();
13311     }
operator ==(StringRef const & other) const13312     auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13313         return
13314             size() == other.size() &&
13315             (std::strncmp( m_start, other.m_start, size() ) == 0);
13316     }
operator !=(StringRef const & other) const13317     auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
13318         return !operator==( other );
13319     }
13320 
operator [](size_type index) const13321     auto StringRef::operator[](size_type index) const noexcept -> char {
13322         return m_start[index];
13323     }
13324 
numberOfCharacters() const13325     auto StringRef::numberOfCharacters() const noexcept -> size_type {
13326         size_type noChars = m_size;
13327         // Make adjustments for uft encodings
13328         for( size_type i=0; i < m_size; ++i ) {
13329             char c = m_start[i];
13330             if( ( c & byte_2_lead ) == byte_2_lead ) {
13331                 noChars--;
13332                 if (( c & byte_3_lead ) == byte_3_lead )
13333                     noChars--;
13334                 if( ( c & byte_4_lead ) == byte_4_lead )
13335                     noChars--;
13336             }
13337         }
13338         return noChars;
13339     }
13340 
operator +(StringRef const & lhs,StringRef const & rhs)13341     auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
13342         std::string str;
13343         str.reserve( lhs.size() + rhs.size() );
13344         str += lhs;
13345         str += rhs;
13346         return str;
13347     }
operator +(StringRef const & lhs,const char * rhs)13348     auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
13349         return std::string( lhs ) + std::string( rhs );
13350     }
operator +(char const * lhs,StringRef const & rhs)13351     auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
13352         return std::string( lhs ) + std::string( rhs );
13353     }
13354 
operator <<(std::ostream & os,StringRef const & str)13355     auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13356         return os.write(str.currentData(), str.size());
13357     }
13358 
operator +=(std::string & lhs,StringRef const & rhs)13359     auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13360         lhs.append(rhs.currentData(), rhs.size());
13361         return lhs;
13362     }
13363 
13364 } // namespace Catch
13365 
13366 #if defined(__clang__)
13367 #    pragma clang diagnostic pop
13368 #endif
13369 // end catch_stringref.cpp
13370 // start catch_tag_alias.cpp
13371 
13372 namespace Catch {
TagAlias(std::string const & _tag,SourceLineInfo _lineInfo)13373     TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13374 }
13375 // end catch_tag_alias.cpp
13376 // start catch_tag_alias_autoregistrar.cpp
13377 
13378 namespace Catch {
13379 
RegistrarForTagAliases(char const * alias,char const * tag,SourceLineInfo const & lineInfo)13380     RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13381         CATCH_TRY {
13382             getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13383         } CATCH_CATCH_ALL {
13384             // Do not throw when constructing global objects, instead register the exception to be processed later
13385             getMutableRegistryHub().registerStartupException();
13386         }
13387     }
13388 
13389 }
13390 // end catch_tag_alias_autoregistrar.cpp
13391 // start catch_tag_alias_registry.cpp
13392 
13393 #include <sstream>
13394 
13395 namespace Catch {
13396 
~TagAliasRegistry()13397     TagAliasRegistry::~TagAliasRegistry() {}
13398 
find(std::string const & alias) const13399     TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13400         auto it = m_registry.find( alias );
13401         if( it != m_registry.end() )
13402             return &(it->second);
13403         else
13404             return nullptr;
13405     }
13406 
expandAliases(std::string const & unexpandedTestSpec) const13407     std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13408         std::string expandedTestSpec = unexpandedTestSpec;
13409         for( auto const& registryKvp : m_registry ) {
13410             std::size_t pos = expandedTestSpec.find( registryKvp.first );
13411             if( pos != std::string::npos ) {
13412                 expandedTestSpec =  expandedTestSpec.substr( 0, pos ) +
13413                                     registryKvp.second.tag +
13414                                     expandedTestSpec.substr( pos + registryKvp.first.size() );
13415             }
13416         }
13417         return expandedTestSpec;
13418     }
13419 
add(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)13420     void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
13421         CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
13422                       "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
13423 
13424         CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13425                       "error: tag alias, '" << alias << "' already registered.\n"
13426                       << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
13427                       << "\tRedefined at: " << lineInfo );
13428     }
13429 
~ITagAliasRegistry()13430     ITagAliasRegistry::~ITagAliasRegistry() {}
13431 
get()13432     ITagAliasRegistry const& ITagAliasRegistry::get() {
13433         return getRegistryHub().getTagAliasRegistry();
13434     }
13435 
13436 } // end namespace Catch
13437 // end catch_tag_alias_registry.cpp
13438 // start catch_test_case_info.cpp
13439 
13440 #include <cctype>
13441 #include <exception>
13442 #include <algorithm>
13443 #include <sstream>
13444 
13445 namespace Catch {
13446 
13447     namespace {
parseSpecialTag(std::string const & tag)13448         TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
13449             if( startsWith( tag, '.' ) ||
13450                 tag == "!hide" )
13451                 return TestCaseInfo::IsHidden;
13452             else if( tag == "!throws" )
13453                 return TestCaseInfo::Throws;
13454             else if( tag == "!shouldfail" )
13455                 return TestCaseInfo::ShouldFail;
13456             else if( tag == "!mayfail" )
13457                 return TestCaseInfo::MayFail;
13458             else if( tag == "!nonportable" )
13459                 return TestCaseInfo::NonPortable;
13460             else if( tag == "!benchmark" )
13461                 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
13462             else
13463                 return TestCaseInfo::None;
13464         }
isReservedTag(std::string const & tag)13465         bool isReservedTag( std::string const& tag ) {
13466             return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
13467         }
enforceNotReservedTag(std::string const & tag,SourceLineInfo const & _lineInfo)13468         void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
13469             CATCH_ENFORCE( !isReservedTag(tag),
13470                           "Tag name: [" << tag << "] is not allowed.\n"
13471                           << "Tag names starting with non alphanumeric characters are reserved\n"
13472                           << _lineInfo );
13473         }
13474     }
13475 
makeTestCase(ITestInvoker * _testCase,std::string const & _className,NameAndTags const & nameAndTags,SourceLineInfo const & _lineInfo)13476     TestCase makeTestCase(  ITestInvoker* _testCase,
13477                             std::string const& _className,
13478                             NameAndTags const& nameAndTags,
13479                             SourceLineInfo const& _lineInfo )
13480     {
13481         bool isHidden = false;
13482 
13483         // Parse out tags
13484         std::vector<std::string> tags;
13485         std::string desc, tag;
13486         bool inTag = false;
13487         std::string _descOrTags = nameAndTags.tags;
13488         for (char c : _descOrTags) {
13489             if( !inTag ) {
13490                 if( c == '[' )
13491                     inTag = true;
13492                 else
13493                     desc += c;
13494             }
13495             else {
13496                 if( c == ']' ) {
13497                     TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
13498                     if( ( prop & TestCaseInfo::IsHidden ) != 0 )
13499                         isHidden = true;
13500                     else if( prop == TestCaseInfo::None )
13501                         enforceNotReservedTag( tag, _lineInfo );
13502 
13503                     // Merged hide tags like `[.approvals]` should be added as
13504                     // `[.][approvals]`. The `[.]` is added at later point, so
13505                     // we only strip the prefix
13506                     if (startsWith(tag, '.') && tag.size() > 1) {
13507                         tag.erase(0, 1);
13508                     }
13509                     tags.push_back( tag );
13510                     tag.clear();
13511                     inTag = false;
13512                 }
13513                 else
13514                     tag += c;
13515             }
13516         }
13517         if( isHidden ) {
13518             tags.push_back( "." );
13519         }
13520 
13521         TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
13522         return TestCase( _testCase, std::move(info) );
13523     }
13524 
setTags(TestCaseInfo & testCaseInfo,std::vector<std::string> tags)13525     void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
13526         std::sort(begin(tags), end(tags));
13527         tags.erase(std::unique(begin(tags), end(tags)), end(tags));
13528         testCaseInfo.lcaseTags.clear();
13529 
13530         for( auto const& tag : tags ) {
13531             std::string lcaseTag = toLower( tag );
13532             testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
13533             testCaseInfo.lcaseTags.push_back( lcaseTag );
13534         }
13535         testCaseInfo.tags = std::move(tags);
13536     }
13537 
TestCaseInfo(std::string const & _name,std::string const & _className,std::string const & _description,std::vector<std::string> const & _tags,SourceLineInfo const & _lineInfo)13538     TestCaseInfo::TestCaseInfo( std::string const& _name,
13539                                 std::string const& _className,
13540                                 std::string const& _description,
13541                                 std::vector<std::string> const& _tags,
13542                                 SourceLineInfo const& _lineInfo )
13543     :   name( _name ),
13544         className( _className ),
13545         description( _description ),
13546         lineInfo( _lineInfo ),
13547         properties( None )
13548     {
13549         setTags( *this, _tags );
13550     }
13551 
isHidden() const13552     bool TestCaseInfo::isHidden() const {
13553         return ( properties & IsHidden ) != 0;
13554     }
throws() const13555     bool TestCaseInfo::throws() const {
13556         return ( properties & Throws ) != 0;
13557     }
okToFail() const13558     bool TestCaseInfo::okToFail() const {
13559         return ( properties & (ShouldFail | MayFail ) ) != 0;
13560     }
expectedToFail() const13561     bool TestCaseInfo::expectedToFail() const {
13562         return ( properties & (ShouldFail ) ) != 0;
13563     }
13564 
tagsAsString() const13565     std::string TestCaseInfo::tagsAsString() const {
13566         std::string ret;
13567         // '[' and ']' per tag
13568         std::size_t full_size = 2 * tags.size();
13569         for (const auto& tag : tags) {
13570             full_size += tag.size();
13571         }
13572         ret.reserve(full_size);
13573         for (const auto& tag : tags) {
13574             ret.push_back('[');
13575             ret.append(tag);
13576             ret.push_back(']');
13577         }
13578 
13579         return ret;
13580     }
13581 
TestCase(ITestInvoker * testCase,TestCaseInfo && info)13582     TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
13583 
withName(std::string const & _newName) const13584     TestCase TestCase::withName( std::string const& _newName ) const {
13585         TestCase other( *this );
13586         other.name = _newName;
13587         return other;
13588     }
13589 
invoke() const13590     void TestCase::invoke() const {
13591         test->invoke();
13592     }
13593 
operator ==(TestCase const & other) const13594     bool TestCase::operator == ( TestCase const& other ) const {
13595         return  test.get() == other.test.get() &&
13596                 name == other.name &&
13597                 className == other.className;
13598     }
13599 
operator <(TestCase const & other) const13600     bool TestCase::operator < ( TestCase const& other ) const {
13601         return name < other.name;
13602     }
13603 
getTestCaseInfo() const13604     TestCaseInfo const& TestCase::getTestCaseInfo() const
13605     {
13606         return *this;
13607     }
13608 
13609 } // end namespace Catch
13610 // end catch_test_case_info.cpp
13611 // start catch_test_case_registry_impl.cpp
13612 
13613 #include <sstream>
13614 
13615 namespace Catch {
13616 
sortTests(IConfig const & config,std::vector<TestCase> const & unsortedTestCases)13617     std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
13618 
13619         std::vector<TestCase> sorted = unsortedTestCases;
13620 
13621         switch( config.runOrder() ) {
13622             case RunTests::InLexicographicalOrder:
13623                 std::sort( sorted.begin(), sorted.end() );
13624                 break;
13625             case RunTests::InRandomOrder:
13626                 seedRng( config );
13627                 std::shuffle( sorted.begin(), sorted.end(), rng() );
13628                 break;
13629             case RunTests::InDeclarationOrder:
13630                 // already in declaration order
13631                 break;
13632         }
13633         return sorted;
13634     }
13635 
isThrowSafe(TestCase const & testCase,IConfig const & config)13636     bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
13637         return !testCase.throws() || config.allowThrows();
13638     }
13639 
matchTest(TestCase const & testCase,TestSpec const & testSpec,IConfig const & config)13640     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
13641         return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
13642     }
13643 
enforceNoDuplicateTestCases(std::vector<TestCase> const & functions)13644     void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
13645         std::set<TestCase> seenFunctions;
13646         for( auto const& function : functions ) {
13647             auto prev = seenFunctions.insert( function );
13648             CATCH_ENFORCE( prev.second,
13649                     "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
13650                     << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
13651                     << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
13652         }
13653     }
13654 
filterTests(std::vector<TestCase> const & testCases,TestSpec const & testSpec,IConfig const & config)13655     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
13656         std::vector<TestCase> filtered;
13657         filtered.reserve( testCases.size() );
13658         for (auto const& testCase : testCases) {
13659             if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
13660                 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
13661                 filtered.push_back(testCase);
13662             }
13663         }
13664         return filtered;
13665     }
getAllTestCasesSorted(IConfig const & config)13666     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
13667         return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
13668     }
13669 
registerTest(TestCase const & testCase)13670     void TestRegistry::registerTest( TestCase const& testCase ) {
13671         std::string name = testCase.getTestCaseInfo().name;
13672         if( name.empty() ) {
13673             ReusableStringStream rss;
13674             rss << "Anonymous test case " << ++m_unnamedCount;
13675             return registerTest( testCase.withName( rss.str() ) );
13676         }
13677         m_functions.push_back( testCase );
13678     }
13679 
getAllTests() const13680     std::vector<TestCase> const& TestRegistry::getAllTests() const {
13681         return m_functions;
13682     }
getAllTestsSorted(IConfig const & config) const13683     std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
13684         if( m_sortedFunctions.empty() )
13685             enforceNoDuplicateTestCases( m_functions );
13686 
13687         if(  m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
13688             m_sortedFunctions = sortTests( config, m_functions );
13689             m_currentSortOrder = config.runOrder();
13690         }
13691         return m_sortedFunctions;
13692     }
13693 
13694     ///////////////////////////////////////////////////////////////////////////
TestInvokerAsFunction(void (* testAsFunction)())13695     TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
13696 
invoke() const13697     void TestInvokerAsFunction::invoke() const {
13698         m_testAsFunction();
13699     }
13700 
extractClassName(StringRef const & classOrQualifiedMethodName)13701     std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
13702         std::string className = classOrQualifiedMethodName;
13703         if( startsWith( className, '&' ) )
13704         {
13705             std::size_t lastColons = className.rfind( "::" );
13706             std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
13707             if( penultimateColons == std::string::npos )
13708                 penultimateColons = 1;
13709             className = className.substr( penultimateColons, lastColons-penultimateColons );
13710         }
13711         return className;
13712     }
13713 
13714 } // end namespace Catch
13715 // end catch_test_case_registry_impl.cpp
13716 // start catch_test_case_tracker.cpp
13717 
13718 #include <algorithm>
13719 #include <cassert>
13720 #include <stdexcept>
13721 #include <memory>
13722 #include <sstream>
13723 
13724 #if defined(__clang__)
13725 #    pragma clang diagnostic push
13726 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
13727 #endif
13728 
13729 namespace Catch {
13730 namespace TestCaseTracking {
13731 
NameAndLocation(std::string const & _name,SourceLineInfo const & _location)13732     NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
13733     :   name( _name ),
13734         location( _location )
13735     {}
13736 
13737     ITracker::~ITracker() = default;
13738 
startRun()13739     ITracker& TrackerContext::startRun() {
13740         m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
13741         m_currentTracker = nullptr;
13742         m_runState = Executing;
13743         return *m_rootTracker;
13744     }
13745 
endRun()13746     void TrackerContext::endRun() {
13747         m_rootTracker.reset();
13748         m_currentTracker = nullptr;
13749         m_runState = NotStarted;
13750     }
13751 
startCycle()13752     void TrackerContext::startCycle() {
13753         m_currentTracker = m_rootTracker.get();
13754         m_runState = Executing;
13755     }
completeCycle()13756     void TrackerContext::completeCycle() {
13757         m_runState = CompletedCycle;
13758     }
13759 
completedCycle() const13760     bool TrackerContext::completedCycle() const {
13761         return m_runState == CompletedCycle;
13762     }
currentTracker()13763     ITracker& TrackerContext::currentTracker() {
13764         return *m_currentTracker;
13765     }
setCurrentTracker(ITracker * tracker)13766     void TrackerContext::setCurrentTracker( ITracker* tracker ) {
13767         m_currentTracker = tracker;
13768     }
13769 
TrackerBase(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)13770     TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
13771     :   m_nameAndLocation( nameAndLocation ),
13772         m_ctx( ctx ),
13773         m_parent( parent )
13774     {}
13775 
nameAndLocation() const13776     NameAndLocation const& TrackerBase::nameAndLocation() const {
13777         return m_nameAndLocation;
13778     }
isComplete() const13779     bool TrackerBase::isComplete() const {
13780         return m_runState == CompletedSuccessfully || m_runState == Failed;
13781     }
isSuccessfullyCompleted() const13782     bool TrackerBase::isSuccessfullyCompleted() const {
13783         return m_runState == CompletedSuccessfully;
13784     }
isOpen() const13785     bool TrackerBase::isOpen() const {
13786         return m_runState != NotStarted && !isComplete();
13787     }
hasChildren() const13788     bool TrackerBase::hasChildren() const {
13789         return !m_children.empty();
13790     }
13791 
addChild(ITrackerPtr const & child)13792     void TrackerBase::addChild( ITrackerPtr const& child ) {
13793         m_children.push_back( child );
13794     }
13795 
findChild(NameAndLocation const & nameAndLocation)13796     ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
13797         auto it = std::find_if( m_children.begin(), m_children.end(),
13798             [&nameAndLocation]( ITrackerPtr const& tracker ){
13799                 return
13800                     tracker->nameAndLocation().location == nameAndLocation.location &&
13801                     tracker->nameAndLocation().name == nameAndLocation.name;
13802             } );
13803         return( it != m_children.end() )
13804             ? *it
13805             : nullptr;
13806     }
parent()13807     ITracker& TrackerBase::parent() {
13808         assert( m_parent ); // Should always be non-null except for root
13809         return *m_parent;
13810     }
13811 
openChild()13812     void TrackerBase::openChild() {
13813         if( m_runState != ExecutingChildren ) {
13814             m_runState = ExecutingChildren;
13815             if( m_parent )
13816                 m_parent->openChild();
13817         }
13818     }
13819 
isSectionTracker() const13820     bool TrackerBase::isSectionTracker() const { return false; }
isGeneratorTracker() const13821     bool TrackerBase::isGeneratorTracker() const { return false; }
13822 
open()13823     void TrackerBase::open() {
13824         m_runState = Executing;
13825         moveToThis();
13826         if( m_parent )
13827             m_parent->openChild();
13828     }
13829 
close()13830     void TrackerBase::close() {
13831 
13832         // Close any still open children (e.g. generators)
13833         while( &m_ctx.currentTracker() != this )
13834             m_ctx.currentTracker().close();
13835 
13836         switch( m_runState ) {
13837             case NeedsAnotherRun:
13838                 break;
13839 
13840             case Executing:
13841                 m_runState = CompletedSuccessfully;
13842                 break;
13843             case ExecutingChildren:
13844                 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
13845                     m_runState = CompletedSuccessfully;
13846                 break;
13847 
13848             case NotStarted:
13849             case CompletedSuccessfully:
13850             case Failed:
13851                 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
13852 
13853             default:
13854                 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
13855         }
13856         moveToParent();
13857         m_ctx.completeCycle();
13858     }
fail()13859     void TrackerBase::fail() {
13860         m_runState = Failed;
13861         if( m_parent )
13862             m_parent->markAsNeedingAnotherRun();
13863         moveToParent();
13864         m_ctx.completeCycle();
13865     }
markAsNeedingAnotherRun()13866     void TrackerBase::markAsNeedingAnotherRun() {
13867         m_runState = NeedsAnotherRun;
13868     }
13869 
moveToParent()13870     void TrackerBase::moveToParent() {
13871         assert( m_parent );
13872         m_ctx.setCurrentTracker( m_parent );
13873     }
moveToThis()13874     void TrackerBase::moveToThis() {
13875         m_ctx.setCurrentTracker( this );
13876     }
13877 
SectionTracker(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)13878     SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
13879     :   TrackerBase( nameAndLocation, ctx, parent )
13880     {
13881         if( parent ) {
13882             while( !parent->isSectionTracker() )
13883                 parent = &parent->parent();
13884 
13885             SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
13886             addNextFilters( parentSection.m_filters );
13887         }
13888     }
13889 
isComplete() const13890     bool SectionTracker::isComplete() const {
13891         bool complete = true;
13892 
13893         if ((m_filters.empty() || m_filters[0] == "") ||
13894              std::find(m_filters.begin(), m_filters.end(),
13895                        m_nameAndLocation.name) != m_filters.end())
13896             complete = TrackerBase::isComplete();
13897         return complete;
13898 
13899     }
13900 
isSectionTracker() const13901     bool SectionTracker::isSectionTracker() const { return true; }
13902 
acquire(TrackerContext & ctx,NameAndLocation const & nameAndLocation)13903     SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
13904         std::shared_ptr<SectionTracker> section;
13905 
13906         ITracker& currentTracker = ctx.currentTracker();
13907         if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
13908             assert( childTracker );
13909             assert( childTracker->isSectionTracker() );
13910             section = std::static_pointer_cast<SectionTracker>( childTracker );
13911         }
13912         else {
13913             section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
13914             currentTracker.addChild( section );
13915         }
13916         if( !ctx.completedCycle() )
13917             section->tryOpen();
13918         return *section;
13919     }
13920 
tryOpen()13921     void SectionTracker::tryOpen() {
13922         if( !isComplete() && (m_filters.empty() || m_filters[0].empty() ||  m_filters[0] == m_nameAndLocation.name ) )
13923             open();
13924     }
13925 
addInitialFilters(std::vector<std::string> const & filters)13926     void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
13927         if( !filters.empty() ) {
13928             m_filters.push_back(""); // Root - should never be consulted
13929             m_filters.push_back(""); // Test Case - not a section filter
13930             m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
13931         }
13932     }
addNextFilters(std::vector<std::string> const & filters)13933     void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
13934         if( filters.size() > 1 )
13935             m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
13936     }
13937 
13938 } // namespace TestCaseTracking
13939 
13940 using TestCaseTracking::ITracker;
13941 using TestCaseTracking::TrackerContext;
13942 using TestCaseTracking::SectionTracker;
13943 
13944 } // namespace Catch
13945 
13946 #if defined(__clang__)
13947 #    pragma clang diagnostic pop
13948 #endif
13949 // end catch_test_case_tracker.cpp
13950 // start catch_test_registry.cpp
13951 
13952 namespace Catch {
13953 
makeTestInvoker(void (* testAsFunction)())13954     auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
13955         return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
13956     }
13957 
NameAndTags(StringRef const & name_,StringRef const & tags_)13958     NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
13959 
AutoReg(ITestInvoker * invoker,SourceLineInfo const & lineInfo,StringRef const & classOrMethod,NameAndTags const & nameAndTags)13960     AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
13961         CATCH_TRY {
13962             getMutableRegistryHub()
13963                     .registerTest(
13964                         makeTestCase(
13965                             invoker,
13966                             extractClassName( classOrMethod ),
13967                             nameAndTags,
13968                             lineInfo));
13969         } CATCH_CATCH_ALL {
13970             // Do not throw when constructing global objects, instead register the exception to be processed later
13971             getMutableRegistryHub().registerStartupException();
13972         }
13973     }
13974 
13975     AutoReg::~AutoReg() = default;
13976 }
13977 // end catch_test_registry.cpp
13978 // start catch_test_spec.cpp
13979 
13980 #include <algorithm>
13981 #include <string>
13982 #include <vector>
13983 #include <memory>
13984 
13985 namespace Catch {
13986 
Pattern(std::string const & name)13987     TestSpec::Pattern::Pattern( std::string const& name )
13988     : m_name( name )
13989     {}
13990 
13991     TestSpec::Pattern::~Pattern() = default;
13992 
name() const13993     std::string const& TestSpec::Pattern::name() const {
13994         return m_name;
13995     }
13996 
NamePattern(std::string const & name,std::string const & filterString)13997     TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
13998     : Pattern( filterString )
13999     , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14000     {}
14001 
matches(TestCaseInfo const & testCase) const14002     bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14003         return m_wildcardPattern.matches( toLower( testCase.name ) );
14004     }
14005 
TagPattern(std::string const & tag,std::string const & filterString)14006     TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14007     : Pattern( filterString )
14008     , m_tag( toLower( tag ) )
14009     {}
14010 
matches(TestCaseInfo const & testCase) const14011     bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14012         return std::find(begin(testCase.lcaseTags),
14013                          end(testCase.lcaseTags),
14014                          m_tag) != end(testCase.lcaseTags);
14015     }
14016 
ExcludedPattern(PatternPtr const & underlyingPattern)14017     TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14018     : Pattern( underlyingPattern->name() )
14019     , m_underlyingPattern( underlyingPattern )
14020     {}
14021 
matches(TestCaseInfo const & testCase) const14022     bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14023         return !m_underlyingPattern->matches( testCase );
14024     }
14025 
matches(TestCaseInfo const & testCase) const14026     bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14027         return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14028     }
14029 
name() const14030     std::string TestSpec::Filter::name() const {
14031         std::string name;
14032         for( auto const& p : m_patterns )
14033             name += p->name();
14034         return name;
14035     }
14036 
hasFilters() const14037     bool TestSpec::hasFilters() const {
14038         return !m_filters.empty();
14039     }
14040 
matches(TestCaseInfo const & testCase) const14041     bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14042         return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14043     }
14044 
matchesByFilter(std::vector<TestCase> const & testCases,IConfig const & config) const14045     TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14046     {
14047         Matches matches( m_filters.size() );
14048         std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14049             std::vector<TestCase const*> currentMatches;
14050             for( auto const& test : testCases )
14051                 if( isThrowSafe( test, config ) && filter.matches( test ) )
14052                     currentMatches.emplace_back( &test );
14053             return FilterMatch{ filter.name(), currentMatches };
14054         } );
14055         return matches;
14056     }
14057 
14058 }
14059 // end catch_test_spec.cpp
14060 // start catch_test_spec_parser.cpp
14061 
14062 namespace Catch {
14063 
TestSpecParser(ITagAliasRegistry const & tagAliases)14064     TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14065 
parse(std::string const & arg)14066     TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14067         m_mode = None;
14068         m_exclusion = false;
14069         m_arg = m_tagAliases->expandAliases( arg );
14070         m_escapeChars.clear();
14071         m_substring.reserve(m_arg.size());
14072         m_patternName.reserve(m_arg.size());
14073         for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14074             visitChar( m_arg[m_pos] );
14075         endMode();
14076         return *this;
14077     }
testSpec()14078     TestSpec TestSpecParser::testSpec() {
14079         addFilter();
14080         return m_testSpec;
14081     }
visitChar(char c)14082     void TestSpecParser::visitChar( char c ) {
14083         if( c == ',' ) {
14084             endMode();
14085             addFilter();
14086             return;
14087         }
14088 
14089         switch( m_mode ) {
14090         case None:
14091             if( processNoneChar( c ) )
14092                 return;
14093             break;
14094         case Name:
14095             processNameChar( c );
14096             break;
14097         case EscapedName:
14098             endMode();
14099             break;
14100         default:
14101         case Tag:
14102         case QuotedName:
14103             if( processOtherChar( c ) )
14104                 return;
14105             break;
14106         }
14107 
14108         m_substring += c;
14109         if( !isControlChar( c ) )
14110             m_patternName += c;
14111     }
14112     // Two of the processing methods return true to signal the caller to return
14113     // without adding the given character to the current pattern strings
processNoneChar(char c)14114     bool TestSpecParser::processNoneChar( char c ) {
14115         switch( c ) {
14116         case ' ':
14117             return true;
14118         case '~':
14119             m_exclusion = true;
14120             return false;
14121         case '[':
14122             startNewMode( Tag );
14123             return false;
14124         case '"':
14125             startNewMode( QuotedName );
14126             return false;
14127         case '\\':
14128             escape();
14129             return true;
14130         default:
14131             startNewMode( Name );
14132             return false;
14133         }
14134     }
processNameChar(char c)14135     void TestSpecParser::processNameChar( char c ) {
14136         if( c == '[' ) {
14137             if( m_substring == "exclude:" )
14138                 m_exclusion = true;
14139             else
14140                 endMode();
14141             startNewMode( Tag );
14142         }
14143     }
processOtherChar(char c)14144     bool TestSpecParser::processOtherChar( char c ) {
14145         if( !isControlChar( c ) )
14146             return false;
14147         m_substring += c;
14148         endMode();
14149         return true;
14150     }
startNewMode(Mode mode)14151     void TestSpecParser::startNewMode( Mode mode ) {
14152         m_mode = mode;
14153     }
endMode()14154     void TestSpecParser::endMode() {
14155         switch( m_mode ) {
14156         case Name:
14157         case QuotedName:
14158             return addPattern<TestSpec::NamePattern>();
14159         case Tag:
14160             return addPattern<TestSpec::TagPattern>();
14161         case EscapedName:
14162             return startNewMode( Name );
14163         case None:
14164         default:
14165             return startNewMode( None );
14166         }
14167     }
escape()14168     void TestSpecParser::escape() {
14169         m_mode = EscapedName;
14170         m_escapeChars.push_back( m_pos );
14171     }
isControlChar(char c) const14172     bool TestSpecParser::isControlChar( char c ) const {
14173         switch( m_mode ) {
14174             default:
14175                 return false;
14176             case None:
14177                 return c == '~';
14178             case Name:
14179                 return c == '[';
14180             case EscapedName:
14181                 return true;
14182             case QuotedName:
14183                 return c == '"';
14184             case Tag:
14185                 return c == '[' || c == ']';
14186         }
14187     }
14188 
addFilter()14189     void TestSpecParser::addFilter() {
14190         if( !m_currentFilter.m_patterns.empty() ) {
14191             m_testSpec.m_filters.push_back( m_currentFilter );
14192             m_currentFilter = TestSpec::Filter();
14193         }
14194     }
14195 
parseTestSpec(std::string const & arg)14196     TestSpec parseTestSpec( std::string const& arg ) {
14197         return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14198     }
14199 
14200 } // namespace Catch
14201 // end catch_test_spec_parser.cpp
14202 // start catch_timer.cpp
14203 
14204 #include <chrono>
14205 
14206 static const uint64_t nanosecondsInSecond = 1000000000;
14207 
14208 namespace Catch {
14209 
getCurrentNanosecondsSinceEpoch()14210     auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14211         return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14212     }
14213 
14214     namespace {
estimateClockResolution()14215         auto estimateClockResolution() -> uint64_t {
14216             uint64_t sum = 0;
14217             static const uint64_t iterations = 1000000;
14218 
14219             auto startTime = getCurrentNanosecondsSinceEpoch();
14220 
14221             for( std::size_t i = 0; i < iterations; ++i ) {
14222 
14223                 uint64_t ticks;
14224                 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14225                 do {
14226                     ticks = getCurrentNanosecondsSinceEpoch();
14227                 } while( ticks == baseTicks );
14228 
14229                 auto delta = ticks - baseTicks;
14230                 sum += delta;
14231 
14232                 // If we have been calibrating for over 3 seconds -- the clock
14233                 // is terrible and we should move on.
14234                 // TBD: How to signal that the measured resolution is probably wrong?
14235                 if (ticks > startTime + 3 * nanosecondsInSecond) {
14236                     return sum / ( i + 1u );
14237                 }
14238             }
14239 
14240             // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14241             // - and potentially do more iterations if there's a high variance.
14242             return sum/iterations;
14243         }
14244     }
getEstimatedClockResolution()14245     auto getEstimatedClockResolution() -> uint64_t {
14246         static auto s_resolution = estimateClockResolution();
14247         return s_resolution;
14248     }
14249 
start()14250     void Timer::start() {
14251        m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14252     }
getElapsedNanoseconds() const14253     auto Timer::getElapsedNanoseconds() const -> uint64_t {
14254         return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14255     }
getElapsedMicroseconds() const14256     auto Timer::getElapsedMicroseconds() const -> uint64_t {
14257         return getElapsedNanoseconds()/1000;
14258     }
getElapsedMilliseconds() const14259     auto Timer::getElapsedMilliseconds() const -> unsigned int {
14260         return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14261     }
getElapsedSeconds() const14262     auto Timer::getElapsedSeconds() const -> double {
14263         return getElapsedMicroseconds()/1000000.0;
14264     }
14265 
14266 } // namespace Catch
14267 // end catch_timer.cpp
14268 // start catch_tostring.cpp
14269 
14270 #if defined(__clang__)
14271 #    pragma clang diagnostic push
14272 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
14273 #    pragma clang diagnostic ignored "-Wglobal-constructors"
14274 #endif
14275 
14276 // Enable specific decls locally
14277 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14278 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
14279 #endif
14280 
14281 #include <cmath>
14282 #include <iomanip>
14283 
14284 namespace Catch {
14285 
14286 namespace Detail {
14287 
14288     const std::string unprintableString = "{?}";
14289 
14290     namespace {
14291         const int hexThreshold = 255;
14292 
14293         struct Endianness {
14294             enum Arch { Big, Little };
14295 
whichCatch::Detail::__anon6485c3de4111::Endianness14296             static Arch which() {
14297                 union _{
14298                     int asInt;
14299                     char asChar[sizeof (int)];
14300                 } u;
14301 
14302                 u.asInt = 1;
14303                 return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
14304             }
14305         };
14306     }
14307 
rawMemoryToString(const void * object,std::size_t size)14308     std::string rawMemoryToString( const void *object, std::size_t size ) {
14309         // Reverse order for little endian architectures
14310         int i = 0, end = static_cast<int>( size ), inc = 1;
14311         if( Endianness::which() == Endianness::Little ) {
14312             i = end-1;
14313             end = inc = -1;
14314         }
14315 
14316         unsigned char const *bytes = static_cast<unsigned char const *>(object);
14317         ReusableStringStream rss;
14318         rss << "0x" << std::setfill('0') << std::hex;
14319         for( ; i != end; i += inc )
14320              rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
14321        return rss.str();
14322     }
14323 }
14324 
14325 template<typename T>
fpToString(T value,int precision)14326 std::string fpToString( T value, int precision ) {
14327     if (Catch::isnan(value)) {
14328         return "nan";
14329     }
14330 
14331     ReusableStringStream rss;
14332     rss << std::setprecision( precision )
14333         << std::fixed
14334         << value;
14335     std::string d = rss.str();
14336     std::size_t i = d.find_last_not_of( '0' );
14337     if( i != std::string::npos && i != d.size()-1 ) {
14338         if( d[i] == '.' )
14339             i++;
14340         d = d.substr( 0, i+1 );
14341     }
14342     return d;
14343 }
14344 
14345 //// ======================================================= ////
14346 //
14347 //   Out-of-line defs for full specialization of StringMaker
14348 //
14349 //// ======================================================= ////
14350 
convert(const std::string & str)14351 std::string StringMaker<std::string>::convert(const std::string& str) {
14352     if (!getCurrentContext().getConfig()->showInvisibles()) {
14353         return '"' + str + '"';
14354     }
14355 
14356     std::string s("\"");
14357     for (char c : str) {
14358         switch (c) {
14359         case '\n':
14360             s.append("\\n");
14361             break;
14362         case '\t':
14363             s.append("\\t");
14364             break;
14365         default:
14366             s.push_back(c);
14367             break;
14368         }
14369     }
14370     s.append("\"");
14371     return s;
14372 }
14373 
14374 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::string_view str)14375 std::string StringMaker<std::string_view>::convert(std::string_view str) {
14376     return ::Catch::Detail::stringify(std::string{ str });
14377 }
14378 #endif
14379 
convert(char const * str)14380 std::string StringMaker<char const*>::convert(char const* str) {
14381     if (str) {
14382         return ::Catch::Detail::stringify(std::string{ str });
14383     } else {
14384         return{ "{null string}" };
14385     }
14386 }
convert(char * str)14387 std::string StringMaker<char*>::convert(char* str) {
14388     if (str) {
14389         return ::Catch::Detail::stringify(std::string{ str });
14390     } else {
14391         return{ "{null string}" };
14392     }
14393 }
14394 
14395 #ifdef CATCH_CONFIG_WCHAR
convert(const std::wstring & wstr)14396 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
14397     std::string s;
14398     s.reserve(wstr.size());
14399     for (auto c : wstr) {
14400         s += (c <= 0xff) ? static_cast<char>(c) : '?';
14401     }
14402     return ::Catch::Detail::stringify(s);
14403 }
14404 
14405 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::wstring_view str)14406 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
14407     return StringMaker<std::wstring>::convert(std::wstring(str));
14408 }
14409 # endif
14410 
convert(wchar_t const * str)14411 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
14412     if (str) {
14413         return ::Catch::Detail::stringify(std::wstring{ str });
14414     } else {
14415         return{ "{null string}" };
14416     }
14417 }
convert(wchar_t * str)14418 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
14419     if (str) {
14420         return ::Catch::Detail::stringify(std::wstring{ str });
14421     } else {
14422         return{ "{null string}" };
14423     }
14424 }
14425 #endif
14426 
14427 #if defined(CATCH_CONFIG_CPP17_BYTE)
14428 #include <cstddef>
convert(std::byte value)14429 std::string StringMaker<std::byte>::convert(std::byte value) {
14430     return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
14431 }
14432 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
14433 
convert(int value)14434 std::string StringMaker<int>::convert(int value) {
14435     return ::Catch::Detail::stringify(static_cast<long long>(value));
14436 }
convert(long value)14437 std::string StringMaker<long>::convert(long value) {
14438     return ::Catch::Detail::stringify(static_cast<long long>(value));
14439 }
convert(long long value)14440 std::string StringMaker<long long>::convert(long long value) {
14441     ReusableStringStream rss;
14442     rss << value;
14443     if (value > Detail::hexThreshold) {
14444         rss << " (0x" << std::hex << value << ')';
14445     }
14446     return rss.str();
14447 }
14448 
convert(unsigned int value)14449 std::string StringMaker<unsigned int>::convert(unsigned int value) {
14450     return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
14451 }
convert(unsigned long value)14452 std::string StringMaker<unsigned long>::convert(unsigned long value) {
14453     return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
14454 }
convert(unsigned long long value)14455 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
14456     ReusableStringStream rss;
14457     rss << value;
14458     if (value > Detail::hexThreshold) {
14459         rss << " (0x" << std::hex << value << ')';
14460     }
14461     return rss.str();
14462 }
14463 
convert(bool b)14464 std::string StringMaker<bool>::convert(bool b) {
14465     return b ? "true" : "false";
14466 }
14467 
convert(signed char value)14468 std::string StringMaker<signed char>::convert(signed char value) {
14469     if (value == '\r') {
14470         return "'\\r'";
14471     } else if (value == '\f') {
14472         return "'\\f'";
14473     } else if (value == '\n') {
14474         return "'\\n'";
14475     } else if (value == '\t') {
14476         return "'\\t'";
14477     } else if ('\0' <= value && value < ' ') {
14478         return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
14479     } else {
14480         char chstr[] = "' '";
14481         chstr[1] = value;
14482         return chstr;
14483     }
14484 }
convert(char c)14485 std::string StringMaker<char>::convert(char c) {
14486     return ::Catch::Detail::stringify(static_cast<signed char>(c));
14487 }
convert(unsigned char c)14488 std::string StringMaker<unsigned char>::convert(unsigned char c) {
14489     return ::Catch::Detail::stringify(static_cast<char>(c));
14490 }
14491 
convert(std::nullptr_t)14492 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
14493     return "nullptr";
14494 }
14495 
14496 int StringMaker<float>::precision = 5;
14497 
convert(float value)14498 std::string StringMaker<float>::convert(float value) {
14499     return fpToString(value, precision) + 'f';
14500 }
14501 
14502 int StringMaker<double>::precision = 10;
14503 
convert(double value)14504 std::string StringMaker<double>::convert(double value) {
14505     return fpToString(value, precision);
14506 }
14507 
symbol()14508 std::string ratio_string<std::atto>::symbol() { return "a"; }
symbol()14509 std::string ratio_string<std::femto>::symbol() { return "f"; }
symbol()14510 std::string ratio_string<std::pico>::symbol() { return "p"; }
symbol()14511 std::string ratio_string<std::nano>::symbol() { return "n"; }
symbol()14512 std::string ratio_string<std::micro>::symbol() { return "u"; }
symbol()14513 std::string ratio_string<std::milli>::symbol() { return "m"; }
14514 
14515 } // end namespace Catch
14516 
14517 #if defined(__clang__)
14518 #    pragma clang diagnostic pop
14519 #endif
14520 
14521 // end catch_tostring.cpp
14522 // start catch_totals.cpp
14523 
14524 namespace Catch {
14525 
operator -(Counts const & other) const14526     Counts Counts::operator - ( Counts const& other ) const {
14527         Counts diff;
14528         diff.passed = passed - other.passed;
14529         diff.failed = failed - other.failed;
14530         diff.failedButOk = failedButOk - other.failedButOk;
14531         return diff;
14532     }
14533 
operator +=(Counts const & other)14534     Counts& Counts::operator += ( Counts const& other ) {
14535         passed += other.passed;
14536         failed += other.failed;
14537         failedButOk += other.failedButOk;
14538         return *this;
14539     }
14540 
total() const14541     std::size_t Counts::total() const {
14542         return passed + failed + failedButOk;
14543     }
allPassed() const14544     bool Counts::allPassed() const {
14545         return failed == 0 && failedButOk == 0;
14546     }
allOk() const14547     bool Counts::allOk() const {
14548         return failed == 0;
14549     }
14550 
operator -(Totals const & other) const14551     Totals Totals::operator - ( Totals const& other ) const {
14552         Totals diff;
14553         diff.assertions = assertions - other.assertions;
14554         diff.testCases = testCases - other.testCases;
14555         return diff;
14556     }
14557 
operator +=(Totals const & other)14558     Totals& Totals::operator += ( Totals const& other ) {
14559         assertions += other.assertions;
14560         testCases += other.testCases;
14561         return *this;
14562     }
14563 
delta(Totals const & prevTotals) const14564     Totals Totals::delta( Totals const& prevTotals ) const {
14565         Totals diff = *this - prevTotals;
14566         if( diff.assertions.failed > 0 )
14567             ++diff.testCases.failed;
14568         else if( diff.assertions.failedButOk > 0 )
14569             ++diff.testCases.failedButOk;
14570         else
14571             ++diff.testCases.passed;
14572         return diff;
14573     }
14574 
14575 }
14576 // end catch_totals.cpp
14577 // start catch_uncaught_exceptions.cpp
14578 
14579 #include <exception>
14580 
14581 namespace Catch {
uncaught_exceptions()14582     bool uncaught_exceptions() {
14583 #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
14584         return std::uncaught_exceptions() > 0;
14585 #else
14586         return std::uncaught_exception();
14587 #endif
14588   }
14589 } // end namespace Catch
14590 // end catch_uncaught_exceptions.cpp
14591 // start catch_version.cpp
14592 
14593 #include <ostream>
14594 
14595 namespace Catch {
14596 
Version(unsigned int _majorVersion,unsigned int _minorVersion,unsigned int _patchNumber,char const * const _branchName,unsigned int _buildNumber)14597     Version::Version
14598         (   unsigned int _majorVersion,
14599             unsigned int _minorVersion,
14600             unsigned int _patchNumber,
14601             char const * const _branchName,
14602             unsigned int _buildNumber )
14603     :   majorVersion( _majorVersion ),
14604         minorVersion( _minorVersion ),
14605         patchNumber( _patchNumber ),
14606         branchName( _branchName ),
14607         buildNumber( _buildNumber )
14608     {}
14609 
operator <<(std::ostream & os,Version const & version)14610     std::ostream& operator << ( std::ostream& os, Version const& version ) {
14611         os  << version.majorVersion << '.'
14612             << version.minorVersion << '.'
14613             << version.patchNumber;
14614         // branchName is never null -> 0th char is \0 if it is empty
14615         if (version.branchName[0]) {
14616             os << '-' << version.branchName
14617                << '.' << version.buildNumber;
14618         }
14619         return os;
14620     }
14621 
libraryVersion()14622     Version const& libraryVersion() {
14623         static Version version( 2, 9, 2, "", 0 );
14624         return version;
14625     }
14626 
14627 }
14628 // end catch_version.cpp
14629 // start catch_wildcard_pattern.cpp
14630 
14631 #include <sstream>
14632 
14633 namespace Catch {
14634 
WildcardPattern(std::string const & pattern,CaseSensitive::Choice caseSensitivity)14635     WildcardPattern::WildcardPattern( std::string const& pattern,
14636                                       CaseSensitive::Choice caseSensitivity )
14637     :   m_caseSensitivity( caseSensitivity ),
14638         m_pattern( adjustCase( pattern ) )
14639     {
14640         if( startsWith( m_pattern, '*' ) ) {
14641             m_pattern = m_pattern.substr( 1 );
14642             m_wildcard = WildcardAtStart;
14643         }
14644         if( endsWith( m_pattern, '*' ) ) {
14645             m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
14646             m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
14647         }
14648     }
14649 
matches(std::string const & str) const14650     bool WildcardPattern::matches( std::string const& str ) const {
14651         switch( m_wildcard ) {
14652             case NoWildcard:
14653                 return m_pattern == adjustCase( str );
14654             case WildcardAtStart:
14655                 return endsWith( adjustCase( str ), m_pattern );
14656             case WildcardAtEnd:
14657                 return startsWith( adjustCase( str ), m_pattern );
14658             case WildcardAtBothEnds:
14659                 return contains( adjustCase( str ), m_pattern );
14660             default:
14661                 CATCH_INTERNAL_ERROR( "Unknown enum" );
14662         }
14663     }
14664 
adjustCase(std::string const & str) const14665     std::string WildcardPattern::adjustCase( std::string const& str ) const {
14666         return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
14667     }
14668 }
14669 // end catch_wildcard_pattern.cpp
14670 // start catch_xmlwriter.cpp
14671 
14672 #include <iomanip>
14673 
14674 using uchar = unsigned char;
14675 
14676 namespace Catch {
14677 
14678 namespace {
14679 
trailingBytes(unsigned char c)14680     size_t trailingBytes(unsigned char c) {
14681         if ((c & 0xE0) == 0xC0) {
14682             return 2;
14683         }
14684         if ((c & 0xF0) == 0xE0) {
14685             return 3;
14686         }
14687         if ((c & 0xF8) == 0xF0) {
14688             return 4;
14689         }
14690         CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
14691     }
14692 
headerValue(unsigned char c)14693     uint32_t headerValue(unsigned char c) {
14694         if ((c & 0xE0) == 0xC0) {
14695             return c & 0x1F;
14696         }
14697         if ((c & 0xF0) == 0xE0) {
14698             return c & 0x0F;
14699         }
14700         if ((c & 0xF8) == 0xF0) {
14701             return c & 0x07;
14702         }
14703         CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
14704     }
14705 
hexEscapeChar(std::ostream & os,unsigned char c)14706     void hexEscapeChar(std::ostream& os, unsigned char c) {
14707         std::ios_base::fmtflags f(os.flags());
14708         os << "\\x"
14709             << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
14710             << static_cast<int>(c);
14711         os.flags(f);
14712     }
14713 
14714 } // anonymous namespace
14715 
XmlEncode(std::string const & str,ForWhat forWhat)14716     XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
14717     :   m_str( str ),
14718         m_forWhat( forWhat )
14719     {}
14720 
encodeTo(std::ostream & os) const14721     void XmlEncode::encodeTo( std::ostream& os ) const {
14722         // Apostrophe escaping not necessary if we always use " to write attributes
14723         // (see: http://www.w3.org/TR/xml/#syntax)
14724 
14725         for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
14726             uchar c = m_str[idx];
14727             switch (c) {
14728             case '<':   os << "&lt;"; break;
14729             case '&':   os << "&amp;"; break;
14730 
14731             case '>':
14732                 // See: http://www.w3.org/TR/xml/#syntax
14733                 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
14734                     os << "&gt;";
14735                 else
14736                     os << c;
14737                 break;
14738 
14739             case '\"':
14740                 if (m_forWhat == ForAttributes)
14741                     os << "&quot;";
14742                 else
14743                     os << c;
14744                 break;
14745 
14746             default:
14747                 // Check for control characters and invalid utf-8
14748 
14749                 // Escape control characters in standard ascii
14750                 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
14751                 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
14752                     hexEscapeChar(os, c);
14753                     break;
14754                 }
14755 
14756                 // Plain ASCII: Write it to stream
14757                 if (c < 0x7F) {
14758                     os << c;
14759                     break;
14760                 }
14761 
14762                 // UTF-8 territory
14763                 // Check if the encoding is valid and if it is not, hex escape bytes.
14764                 // Important: We do not check the exact decoded values for validity, only the encoding format
14765                 // First check that this bytes is a valid lead byte:
14766                 // This means that it is not encoded as 1111 1XXX
14767                 // Or as 10XX XXXX
14768                 if (c <  0xC0 ||
14769                     c >= 0xF8) {
14770                     hexEscapeChar(os, c);
14771                     break;
14772                 }
14773 
14774                 auto encBytes = trailingBytes(c);
14775                 // Are there enough bytes left to avoid accessing out-of-bounds memory?
14776                 if (idx + encBytes - 1 >= m_str.size()) {
14777                     hexEscapeChar(os, c);
14778                     break;
14779                 }
14780                 // The header is valid, check data
14781                 // The next encBytes bytes must together be a valid utf-8
14782                 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
14783                 bool valid = true;
14784                 uint32_t value = headerValue(c);
14785                 for (std::size_t n = 1; n < encBytes; ++n) {
14786                     uchar nc = m_str[idx + n];
14787                     valid &= ((nc & 0xC0) == 0x80);
14788                     value = (value << 6) | (nc & 0x3F);
14789                 }
14790 
14791                 if (
14792                     // Wrong bit pattern of following bytes
14793                     (!valid) ||
14794                     // Overlong encodings
14795                     (value < 0x80) ||
14796                     (0x80 <= value && value < 0x800   && encBytes > 2) ||
14797                     (0x800 < value && value < 0x10000 && encBytes > 3) ||
14798                     // Encoded value out of range
14799                     (value >= 0x110000)
14800                     ) {
14801                     hexEscapeChar(os, c);
14802                     break;
14803                 }
14804 
14805                 // If we got here, this is in fact a valid(ish) utf-8 sequence
14806                 for (std::size_t n = 0; n < encBytes; ++n) {
14807                     os << m_str[idx + n];
14808                 }
14809                 idx += encBytes - 1;
14810                 break;
14811             }
14812         }
14813     }
14814 
operator <<(std::ostream & os,XmlEncode const & xmlEncode)14815     std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
14816         xmlEncode.encodeTo( os );
14817         return os;
14818     }
14819 
ScopedElement(XmlWriter * writer)14820     XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
14821     :   m_writer( writer )
14822     {}
14823 
ScopedElement(ScopedElement && other)14824     XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
14825     :   m_writer( other.m_writer ){
14826         other.m_writer = nullptr;
14827     }
operator =(ScopedElement && other)14828     XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
14829         if ( m_writer ) {
14830             m_writer->endElement();
14831         }
14832         m_writer = other.m_writer;
14833         other.m_writer = nullptr;
14834         return *this;
14835     }
14836 
~ScopedElement()14837     XmlWriter::ScopedElement::~ScopedElement() {
14838         if( m_writer )
14839             m_writer->endElement();
14840     }
14841 
writeText(std::string const & text,bool indent)14842     XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
14843         m_writer->writeText( text, indent );
14844         return *this;
14845     }
14846 
XmlWriter(std::ostream & os)14847     XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
14848     {
14849         writeDeclaration();
14850     }
14851 
~XmlWriter()14852     XmlWriter::~XmlWriter() {
14853         while( !m_tags.empty() )
14854             endElement();
14855     }
14856 
startElement(std::string const & name)14857     XmlWriter& XmlWriter::startElement( std::string const& name ) {
14858         ensureTagClosed();
14859         newlineIfNecessary();
14860         m_os << m_indent << '<' << name;
14861         m_tags.push_back( name );
14862         m_indent += "  ";
14863         m_tagIsOpen = true;
14864         return *this;
14865     }
14866 
scopedElement(std::string const & name)14867     XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
14868         ScopedElement scoped( this );
14869         startElement( name );
14870         return scoped;
14871     }
14872 
endElement()14873     XmlWriter& XmlWriter::endElement() {
14874         newlineIfNecessary();
14875         m_indent = m_indent.substr( 0, m_indent.size()-2 );
14876         if( m_tagIsOpen ) {
14877             m_os << "/>";
14878             m_tagIsOpen = false;
14879         }
14880         else {
14881             m_os << m_indent << "</" << m_tags.back() << ">";
14882         }
14883         m_os << std::endl;
14884         m_tags.pop_back();
14885         return *this;
14886     }
14887 
writeAttribute(std::string const & name,std::string const & attribute)14888     XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
14889         if( !name.empty() && !attribute.empty() )
14890             m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
14891         return *this;
14892     }
14893 
writeAttribute(std::string const & name,bool attribute)14894     XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
14895         m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
14896         return *this;
14897     }
14898 
writeText(std::string const & text,bool indent)14899     XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
14900         if( !text.empty() ){
14901             bool tagWasOpen = m_tagIsOpen;
14902             ensureTagClosed();
14903             if( tagWasOpen && indent )
14904                 m_os << m_indent;
14905             m_os << XmlEncode( text );
14906             m_needsNewline = true;
14907         }
14908         return *this;
14909     }
14910 
writeComment(std::string const & text)14911     XmlWriter& XmlWriter::writeComment( std::string const& text ) {
14912         ensureTagClosed();
14913         m_os << m_indent << "<!--" << text << "-->";
14914         m_needsNewline = true;
14915         return *this;
14916     }
14917 
writeStylesheetRef(std::string const & url)14918     void XmlWriter::writeStylesheetRef( std::string const& url ) {
14919         m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
14920     }
14921 
writeBlankLine()14922     XmlWriter& XmlWriter::writeBlankLine() {
14923         ensureTagClosed();
14924         m_os << '\n';
14925         return *this;
14926     }
14927 
ensureTagClosed()14928     void XmlWriter::ensureTagClosed() {
14929         if( m_tagIsOpen ) {
14930             m_os << ">" << std::endl;
14931             m_tagIsOpen = false;
14932         }
14933     }
14934 
writeDeclaration()14935     void XmlWriter::writeDeclaration() {
14936         m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
14937     }
14938 
newlineIfNecessary()14939     void XmlWriter::newlineIfNecessary() {
14940         if( m_needsNewline ) {
14941             m_os << std::endl;
14942             m_needsNewline = false;
14943         }
14944     }
14945 }
14946 // end catch_xmlwriter.cpp
14947 // start catch_reporter_bases.cpp
14948 
14949 #include <cstring>
14950 #include <cfloat>
14951 #include <cstdio>
14952 #include <cassert>
14953 #include <memory>
14954 
14955 namespace Catch {
prepareExpandedExpression(AssertionResult & result)14956     void prepareExpandedExpression(AssertionResult& result) {
14957         result.getExpandedExpression();
14958     }
14959 
14960     // Because formatting using c++ streams is stateful, drop down to C is required
14961     // Alternatively we could use stringstream, but its performance is... not good.
getFormattedDuration(double duration)14962     std::string getFormattedDuration( double duration ) {
14963         // Max exponent + 1 is required to represent the whole part
14964         // + 1 for decimal point
14965         // + 3 for the 3 decimal places
14966         // + 1 for null terminator
14967         const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
14968         char buffer[maxDoubleSize];
14969 
14970         // Save previous errno, to prevent sprintf from overwriting it
14971         ErrnoGuard guard;
14972 #ifdef _MSC_VER
14973         sprintf_s(buffer, "%.3f", duration);
14974 #else
14975         std::sprintf(buffer, "%.3f", duration);
14976 #endif
14977         return std::string(buffer);
14978     }
14979 
serializeFilters(std::vector<std::string> const & container)14980     std::string serializeFilters( std::vector<std::string> const& container ) {
14981         ReusableStringStream oss;
14982         bool first = true;
14983         for (auto&& filter : container)
14984         {
14985             if (!first)
14986                 oss << ' ';
14987             else
14988                 first = false;
14989 
14990             oss << filter;
14991         }
14992         return oss.str();
14993     }
14994 
TestEventListenerBase(ReporterConfig const & _config)14995     TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
14996         :StreamingReporterBase(_config) {}
14997 
getSupportedVerbosities()14998     std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
14999         return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15000     }
15001 
assertionStarting(AssertionInfo const &)15002     void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15003 
assertionEnded(AssertionStats const &)15004     bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15005         return false;
15006     }
15007 
15008 } // end namespace Catch
15009 // end catch_reporter_bases.cpp
15010 // start catch_reporter_compact.cpp
15011 
15012 namespace {
15013 
15014 #ifdef CATCH_PLATFORM_MAC
failedString()15015     const char* failedString() { return "FAILED"; }
passedString()15016     const char* passedString() { return "PASSED"; }
15017 #else
15018     const char* failedString() { return "failed"; }
15019     const char* passedString() { return "passed"; }
15020 #endif
15021 
15022     // Colour::LightGrey
dimColour()15023     Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15024 
bothOrAll(std::size_t count)15025     std::string bothOrAll( std::size_t count ) {
15026         return count == 1 ? std::string() :
15027                count == 2 ? "both " : "all " ;
15028     }
15029 
15030 } // anon namespace
15031 
15032 namespace Catch {
15033 namespace {
15034 // Colour, message variants:
15035 // - white: No tests ran.
15036 // -   red: Failed [both/all] N test cases, failed [both/all] M assertions.
15037 // - white: Passed [both/all] N test cases (no assertions).
15038 // -   red: Failed N tests cases, failed M assertions.
15039 // - green: Passed [both/all] N tests cases with M assertions.
printTotals(std::ostream & out,const Totals & totals)15040 void printTotals(std::ostream& out, const Totals& totals) {
15041     if (totals.testCases.total() == 0) {
15042         out << "No tests ran.";
15043     } else if (totals.testCases.failed == totals.testCases.total()) {
15044         Colour colour(Colour::ResultError);
15045         const std::string qualify_assertions_failed =
15046             totals.assertions.failed == totals.assertions.total() ?
15047             bothOrAll(totals.assertions.failed) : std::string();
15048         out <<
15049             "Failed " << bothOrAll(totals.testCases.failed)
15050             << pluralise(totals.testCases.failed, "test case") << ", "
15051             "failed " << qualify_assertions_failed <<
15052             pluralise(totals.assertions.failed, "assertion") << '.';
15053     } else if (totals.assertions.total() == 0) {
15054         out <<
15055             "Passed " << bothOrAll(totals.testCases.total())
15056             << pluralise(totals.testCases.total(), "test case")
15057             << " (no assertions).";
15058     } else if (totals.assertions.failed) {
15059         Colour colour(Colour::ResultError);
15060         out <<
15061             "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15062             "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15063     } else {
15064         Colour colour(Colour::ResultSuccess);
15065         out <<
15066             "Passed " << bothOrAll(totals.testCases.passed)
15067             << pluralise(totals.testCases.passed, "test case") <<
15068             " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15069     }
15070 }
15071 
15072 // Implementation of CompactReporter formatting
15073 class AssertionPrinter {
15074 public:
15075     AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15076     AssertionPrinter(AssertionPrinter const&) = delete;
AssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15077     AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15078         : stream(_stream)
15079         , result(_stats.assertionResult)
15080         , messages(_stats.infoMessages)
15081         , itMessage(_stats.infoMessages.begin())
15082         , printInfoMessages(_printInfoMessages) {}
15083 
print()15084     void print() {
15085         printSourceInfo();
15086 
15087         itMessage = messages.begin();
15088 
15089         switch (result.getResultType()) {
15090         case ResultWas::Ok:
15091             printResultType(Colour::ResultSuccess, passedString());
15092             printOriginalExpression();
15093             printReconstructedExpression();
15094             if (!result.hasExpression())
15095                 printRemainingMessages(Colour::None);
15096             else
15097                 printRemainingMessages();
15098             break;
15099         case ResultWas::ExpressionFailed:
15100             if (result.isOk())
15101                 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15102             else
15103                 printResultType(Colour::Error, failedString());
15104             printOriginalExpression();
15105             printReconstructedExpression();
15106             printRemainingMessages();
15107             break;
15108         case ResultWas::ThrewException:
15109             printResultType(Colour::Error, failedString());
15110             printIssue("unexpected exception with message:");
15111             printMessage();
15112             printExpressionWas();
15113             printRemainingMessages();
15114             break;
15115         case ResultWas::FatalErrorCondition:
15116             printResultType(Colour::Error, failedString());
15117             printIssue("fatal error condition with message:");
15118             printMessage();
15119             printExpressionWas();
15120             printRemainingMessages();
15121             break;
15122         case ResultWas::DidntThrowException:
15123             printResultType(Colour::Error, failedString());
15124             printIssue("expected exception, got none");
15125             printExpressionWas();
15126             printRemainingMessages();
15127             break;
15128         case ResultWas::Info:
15129             printResultType(Colour::None, "info");
15130             printMessage();
15131             printRemainingMessages();
15132             break;
15133         case ResultWas::Warning:
15134             printResultType(Colour::None, "warning");
15135             printMessage();
15136             printRemainingMessages();
15137             break;
15138         case ResultWas::ExplicitFailure:
15139             printResultType(Colour::Error, failedString());
15140             printIssue("explicitly");
15141             printRemainingMessages(Colour::None);
15142             break;
15143             // These cases are here to prevent compiler warnings
15144         case ResultWas::Unknown:
15145         case ResultWas::FailureBit:
15146         case ResultWas::Exception:
15147             printResultType(Colour::Error, "** internal error **");
15148             break;
15149         }
15150     }
15151 
15152 private:
printSourceInfo() const15153     void printSourceInfo() const {
15154         Colour colourGuard(Colour::FileName);
15155         stream << result.getSourceInfo() << ':';
15156     }
15157 
printResultType(Colour::Code colour,std::string const & passOrFail) const15158     void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15159         if (!passOrFail.empty()) {
15160             {
15161                 Colour colourGuard(colour);
15162                 stream << ' ' << passOrFail;
15163             }
15164             stream << ':';
15165         }
15166     }
15167 
printIssue(std::string const & issue) const15168     void printIssue(std::string const& issue) const {
15169         stream << ' ' << issue;
15170     }
15171 
printExpressionWas()15172     void printExpressionWas() {
15173         if (result.hasExpression()) {
15174             stream << ';';
15175             {
15176                 Colour colour(dimColour());
15177                 stream << " expression was:";
15178             }
15179             printOriginalExpression();
15180         }
15181     }
15182 
printOriginalExpression() const15183     void printOriginalExpression() const {
15184         if (result.hasExpression()) {
15185             stream << ' ' << result.getExpression();
15186         }
15187     }
15188 
printReconstructedExpression() const15189     void printReconstructedExpression() const {
15190         if (result.hasExpandedExpression()) {
15191             {
15192                 Colour colour(dimColour());
15193                 stream << " for: ";
15194             }
15195             stream << result.getExpandedExpression();
15196         }
15197     }
15198 
printMessage()15199     void printMessage() {
15200         if (itMessage != messages.end()) {
15201             stream << " '" << itMessage->message << '\'';
15202             ++itMessage;
15203         }
15204     }
15205 
printRemainingMessages(Colour::Code colour=dimColour ())15206     void printRemainingMessages(Colour::Code colour = dimColour()) {
15207         if (itMessage == messages.end())
15208             return;
15209 
15210         const auto itEnd = messages.cend();
15211         const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
15212 
15213         {
15214             Colour colourGuard(colour);
15215             stream << " with " << pluralise(N, "message") << ':';
15216         }
15217 
15218         while (itMessage != itEnd) {
15219             // If this assertion is a warning ignore any INFO messages
15220             if (printInfoMessages || itMessage->type != ResultWas::Info) {
15221                 printMessage();
15222                 if (itMessage != itEnd) {
15223                     Colour colourGuard(dimColour());
15224                     stream << " and";
15225                 }
15226                 continue;
15227             }
15228             ++itMessage;
15229         }
15230     }
15231 
15232 private:
15233     std::ostream& stream;
15234     AssertionResult const& result;
15235     std::vector<MessageInfo> messages;
15236     std::vector<MessageInfo>::const_iterator itMessage;
15237     bool printInfoMessages;
15238 };
15239 
15240 } // anon namespace
15241 
getDescription()15242         std::string CompactReporter::getDescription() {
15243             return "Reports test results on a single line, suitable for IDEs";
15244         }
15245 
getPreferences() const15246         ReporterPreferences CompactReporter::getPreferences() const {
15247             return m_reporterPrefs;
15248         }
15249 
noMatchingTestCases(std::string const & spec)15250         void CompactReporter::noMatchingTestCases( std::string const& spec ) {
15251             stream << "No test cases matched '" << spec << '\'' << std::endl;
15252         }
15253 
assertionStarting(AssertionInfo const &)15254         void CompactReporter::assertionStarting( AssertionInfo const& ) {}
15255 
assertionEnded(AssertionStats const & _assertionStats)15256         bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
15257             AssertionResult const& result = _assertionStats.assertionResult;
15258 
15259             bool printInfoMessages = true;
15260 
15261             // Drop out if result was successful and we're not printing those
15262             if( !m_config->includeSuccessfulResults() && result.isOk() ) {
15263                 if( result.getResultType() != ResultWas::Warning )
15264                     return false;
15265                 printInfoMessages = false;
15266             }
15267 
15268             AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
15269             printer.print();
15270 
15271             stream << std::endl;
15272             return true;
15273         }
15274 
sectionEnded(SectionStats const & _sectionStats)15275         void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
15276             if (m_config->showDurations() == ShowDurations::Always) {
15277                 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
15278             }
15279         }
15280 
testRunEnded(TestRunStats const & _testRunStats)15281         void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
15282             printTotals( stream, _testRunStats.totals );
15283             stream << '\n' << std::endl;
15284             StreamingReporterBase::testRunEnded( _testRunStats );
15285         }
15286 
~CompactReporter()15287         CompactReporter::~CompactReporter() {}
15288 
15289     CATCH_REGISTER_REPORTER( "compact", CompactReporter )
15290 
15291 } // end namespace Catch
15292 // end catch_reporter_compact.cpp
15293 // start catch_reporter_console.cpp
15294 
15295 #include <cfloat>
15296 #include <cstdio>
15297 
15298 #if defined(_MSC_VER)
15299 #pragma warning(push)
15300 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
15301  // Note that 4062 (not all labels are handled and default is missing) is enabled
15302 #endif
15303 
15304 #if defined(__clang__)
15305 #  pragma clang diagnostic push
15306 // For simplicity, benchmarking-only helpers are always enabled
15307 #  pragma clang diagnostic ignored "-Wunused-function"
15308 #endif
15309 
15310 namespace Catch {
15311 
15312 namespace {
15313 
15314 // Formatter impl for ConsoleReporter
15315 class ConsoleAssertionPrinter {
15316 public:
15317     ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
15318     ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15319     ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15320         : stream(_stream),
15321         stats(_stats),
15322         result(_stats.assertionResult),
15323         colour(Colour::None),
15324         message(result.getMessage()),
15325         messages(_stats.infoMessages),
15326         printInfoMessages(_printInfoMessages) {
15327         switch (result.getResultType()) {
15328         case ResultWas::Ok:
15329             colour = Colour::Success;
15330             passOrFail = "PASSED";
15331             //if( result.hasMessage() )
15332             if (_stats.infoMessages.size() == 1)
15333                 messageLabel = "with message";
15334             if (_stats.infoMessages.size() > 1)
15335                 messageLabel = "with messages";
15336             break;
15337         case ResultWas::ExpressionFailed:
15338             if (result.isOk()) {
15339                 colour = Colour::Success;
15340                 passOrFail = "FAILED - but was ok";
15341             } else {
15342                 colour = Colour::Error;
15343                 passOrFail = "FAILED";
15344             }
15345             if (_stats.infoMessages.size() == 1)
15346                 messageLabel = "with message";
15347             if (_stats.infoMessages.size() > 1)
15348                 messageLabel = "with messages";
15349             break;
15350         case ResultWas::ThrewException:
15351             colour = Colour::Error;
15352             passOrFail = "FAILED";
15353             messageLabel = "due to unexpected exception with ";
15354             if (_stats.infoMessages.size() == 1)
15355                 messageLabel += "message";
15356             if (_stats.infoMessages.size() > 1)
15357                 messageLabel += "messages";
15358             break;
15359         case ResultWas::FatalErrorCondition:
15360             colour = Colour::Error;
15361             passOrFail = "FAILED";
15362             messageLabel = "due to a fatal error condition";
15363             break;
15364         case ResultWas::DidntThrowException:
15365             colour = Colour::Error;
15366             passOrFail = "FAILED";
15367             messageLabel = "because no exception was thrown where one was expected";
15368             break;
15369         case ResultWas::Info:
15370             messageLabel = "info";
15371             break;
15372         case ResultWas::Warning:
15373             messageLabel = "warning";
15374             break;
15375         case ResultWas::ExplicitFailure:
15376             passOrFail = "FAILED";
15377             colour = Colour::Error;
15378             if (_stats.infoMessages.size() == 1)
15379                 messageLabel = "explicitly with message";
15380             if (_stats.infoMessages.size() > 1)
15381                 messageLabel = "explicitly with messages";
15382             break;
15383             // These cases are here to prevent compiler warnings
15384         case ResultWas::Unknown:
15385         case ResultWas::FailureBit:
15386         case ResultWas::Exception:
15387             passOrFail = "** internal error **";
15388             colour = Colour::Error;
15389             break;
15390         }
15391     }
15392 
print() const15393     void print() const {
15394         printSourceInfo();
15395         if (stats.totals.assertions.total() > 0) {
15396             printResultType();
15397             printOriginalExpression();
15398             printReconstructedExpression();
15399         } else {
15400             stream << '\n';
15401         }
15402         printMessage();
15403     }
15404 
15405 private:
printResultType() const15406     void printResultType() const {
15407         if (!passOrFail.empty()) {
15408             Colour colourGuard(colour);
15409             stream << passOrFail << ":\n";
15410         }
15411     }
printOriginalExpression() const15412     void printOriginalExpression() const {
15413         if (result.hasExpression()) {
15414             Colour colourGuard(Colour::OriginalExpression);
15415             stream << "  ";
15416             stream << result.getExpressionInMacro();
15417             stream << '\n';
15418         }
15419     }
printReconstructedExpression() const15420     void printReconstructedExpression() const {
15421         if (result.hasExpandedExpression()) {
15422             stream << "with expansion:\n";
15423             Colour colourGuard(Colour::ReconstructedExpression);
15424             stream << Column(result.getExpandedExpression()).indent(2) << '\n';
15425         }
15426     }
printMessage() const15427     void printMessage() const {
15428         if (!messageLabel.empty())
15429             stream << messageLabel << ':' << '\n';
15430         for (auto const& msg : messages) {
15431             // If this assertion is a warning ignore any INFO messages
15432             if (printInfoMessages || msg.type != ResultWas::Info)
15433                 stream << Column(msg.message).indent(2) << '\n';
15434         }
15435     }
printSourceInfo() const15436     void printSourceInfo() const {
15437         Colour colourGuard(Colour::FileName);
15438         stream << result.getSourceInfo() << ": ";
15439     }
15440 
15441     std::ostream& stream;
15442     AssertionStats const& stats;
15443     AssertionResult const& result;
15444     Colour::Code colour;
15445     std::string passOrFail;
15446     std::string messageLabel;
15447     std::string message;
15448     std::vector<MessageInfo> messages;
15449     bool printInfoMessages;
15450 };
15451 
makeRatio(std::size_t number,std::size_t total)15452 std::size_t makeRatio(std::size_t number, std::size_t total) {
15453     std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
15454     return (ratio == 0 && number > 0) ? 1 : ratio;
15455 }
15456 
findMax(std::size_t & i,std::size_t & j,std::size_t & k)15457 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
15458     if (i > j && i > k)
15459         return i;
15460     else if (j > k)
15461         return j;
15462     else
15463         return k;
15464 }
15465 
15466 struct ColumnInfo {
15467     enum Justification { Left, Right };
15468     std::string name;
15469     int width;
15470     Justification justification;
15471 };
15472 struct ColumnBreak {};
15473 struct RowBreak {};
15474 
15475 class Duration {
15476     enum class Unit {
15477         Auto,
15478         Nanoseconds,
15479         Microseconds,
15480         Milliseconds,
15481         Seconds,
15482         Minutes
15483     };
15484     static const uint64_t s_nanosecondsInAMicrosecond = 1000;
15485     static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
15486     static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
15487     static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
15488 
15489     uint64_t m_inNanoseconds;
15490     Unit m_units;
15491 
15492 public:
Duration(double inNanoseconds,Unit units=Unit::Auto)15493 	explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
15494         : Duration(static_cast<uint64_t>(inNanoseconds), units) {
15495     }
15496 
Duration(uint64_t inNanoseconds,Unit units=Unit::Auto)15497     explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
15498         : m_inNanoseconds(inNanoseconds),
15499         m_units(units) {
15500         if (m_units == Unit::Auto) {
15501             if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
15502                 m_units = Unit::Nanoseconds;
15503             else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
15504                 m_units = Unit::Microseconds;
15505             else if (m_inNanoseconds < s_nanosecondsInASecond)
15506                 m_units = Unit::Milliseconds;
15507             else if (m_inNanoseconds < s_nanosecondsInAMinute)
15508                 m_units = Unit::Seconds;
15509             else
15510                 m_units = Unit::Minutes;
15511         }
15512 
15513     }
15514 
value() const15515     auto value() const -> double {
15516         switch (m_units) {
15517         case Unit::Microseconds:
15518             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
15519         case Unit::Milliseconds:
15520             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
15521         case Unit::Seconds:
15522             return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
15523         case Unit::Minutes:
15524             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
15525         default:
15526             return static_cast<double>(m_inNanoseconds);
15527         }
15528     }
unitsAsString() const15529     auto unitsAsString() const -> std::string {
15530         switch (m_units) {
15531         case Unit::Nanoseconds:
15532             return "ns";
15533         case Unit::Microseconds:
15534             return "us";
15535         case Unit::Milliseconds:
15536             return "ms";
15537         case Unit::Seconds:
15538             return "s";
15539         case Unit::Minutes:
15540             return "m";
15541         default:
15542             return "** internal error **";
15543         }
15544 
15545     }
operator <<(std::ostream & os,Duration const & duration)15546     friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
15547         return os << duration.value() << " " << duration.unitsAsString();
15548     }
15549 };
15550 } // end anon namespace
15551 
15552 class TablePrinter {
15553     std::ostream& m_os;
15554     std::vector<ColumnInfo> m_columnInfos;
15555     std::ostringstream m_oss;
15556     int m_currentColumn = -1;
15557     bool m_isOpen = false;
15558 
15559 public:
TablePrinter(std::ostream & os,std::vector<ColumnInfo> columnInfos)15560     TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
15561     :   m_os( os ),
15562         m_columnInfos( std::move( columnInfos ) ) {}
15563 
columnInfos() const15564     auto columnInfos() const -> std::vector<ColumnInfo> const& {
15565         return m_columnInfos;
15566     }
15567 
open()15568     void open() {
15569         if (!m_isOpen) {
15570             m_isOpen = true;
15571             *this << RowBreak();
15572 
15573 			Columns headerCols;
15574 			Spacer spacer(2);
15575 			for (auto const& info : m_columnInfos) {
15576 				headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
15577 				headerCols += spacer;
15578 			}
15579 			m_os << headerCols << "\n";
15580 
15581             m_os << Catch::getLineOfChars<'-'>() << "\n";
15582         }
15583     }
close()15584     void close() {
15585         if (m_isOpen) {
15586             *this << RowBreak();
15587             m_os << std::endl;
15588             m_isOpen = false;
15589         }
15590     }
15591 
15592     template<typename T>
operator <<(TablePrinter & tp,T const & value)15593     friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
15594         tp.m_oss << value;
15595         return tp;
15596     }
15597 
operator <<(TablePrinter & tp,ColumnBreak)15598     friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
15599         auto colStr = tp.m_oss.str();
15600         // This takes account of utf8 encodings
15601         auto strSize = Catch::StringRef(colStr).numberOfCharacters();
15602         tp.m_oss.str("");
15603         tp.open();
15604         if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
15605             tp.m_currentColumn = -1;
15606             tp.m_os << "\n";
15607         }
15608         tp.m_currentColumn++;
15609 
15610         auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
15611         auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
15612             ? std::string(colInfo.width - (strSize + 2), ' ')
15613             : std::string();
15614         if (colInfo.justification == ColumnInfo::Left)
15615             tp.m_os << colStr << padding << " ";
15616         else
15617             tp.m_os << padding << colStr << " ";
15618         return tp;
15619     }
15620 
operator <<(TablePrinter & tp,RowBreak)15621     friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
15622         if (tp.m_currentColumn > 0) {
15623             tp.m_os << "\n";
15624             tp.m_currentColumn = -1;
15625         }
15626         return tp;
15627     }
15628 };
15629 
ConsoleReporter(ReporterConfig const & config)15630 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
15631     : StreamingReporterBase(config),
15632     m_tablePrinter(new TablePrinter(config.stream(),
15633     {
15634         { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
15635         { "samples      mean       std dev", 14, ColumnInfo::Right },
15636         { "iterations   low mean   low std dev", 14, ColumnInfo::Right },
15637         { "estimated    high mean  high std dev", 14, ColumnInfo::Right }
15638     })) {}
15639 ConsoleReporter::~ConsoleReporter() = default;
15640 
getDescription()15641 std::string ConsoleReporter::getDescription() {
15642     return "Reports test results as plain lines of text";
15643 }
15644 
noMatchingTestCases(std::string const & spec)15645 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
15646     stream << "No test cases matched '" << spec << '\'' << std::endl;
15647 }
15648 
assertionStarting(AssertionInfo const &)15649 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
15650 
assertionEnded(AssertionStats const & _assertionStats)15651 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
15652     AssertionResult const& result = _assertionStats.assertionResult;
15653 
15654     bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
15655 
15656     // Drop out if result was successful but we're not printing them.
15657     if (!includeResults && result.getResultType() != ResultWas::Warning)
15658         return false;
15659 
15660     lazyPrint();
15661 
15662     ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
15663     printer.print();
15664     stream << std::endl;
15665     return true;
15666 }
15667 
sectionStarting(SectionInfo const & _sectionInfo)15668 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
15669     m_tablePrinter->close();
15670     m_headerPrinted = false;
15671     StreamingReporterBase::sectionStarting(_sectionInfo);
15672 }
sectionEnded(SectionStats const & _sectionStats)15673 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
15674     m_tablePrinter->close();
15675     if (_sectionStats.missingAssertions) {
15676         lazyPrint();
15677         Colour colour(Colour::ResultError);
15678         if (m_sectionStack.size() > 1)
15679             stream << "\nNo assertions in section";
15680         else
15681             stream << "\nNo assertions in test case";
15682         stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
15683     }
15684     if (m_config->showDurations() == ShowDurations::Always) {
15685         stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
15686     }
15687     if (m_headerPrinted) {
15688         m_headerPrinted = false;
15689     }
15690     StreamingReporterBase::sectionEnded(_sectionStats);
15691 }
15692 
15693 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)15694 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
15695 	lazyPrintWithoutClosingBenchmarkTable();
15696 
15697 	auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
15698 
15699 	bool firstLine = true;
15700 	for (auto line : nameCol) {
15701 		if (!firstLine)
15702 			(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
15703 		else
15704 			firstLine = false;
15705 
15706 		(*m_tablePrinter) << line << ColumnBreak();
15707 	}
15708 }
15709 
benchmarkStarting(BenchmarkInfo const & info)15710 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
15711 	(*m_tablePrinter) << info.samples << ColumnBreak()
15712 		<< info.iterations << ColumnBreak()
15713 		<< Duration(info.estimatedDuration) << ColumnBreak();
15714 }
benchmarkEnded(BenchmarkStats<> const & stats)15715 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
15716 	(*m_tablePrinter) << ColumnBreak()
15717 		<< Duration(stats.mean.point.count()) << ColumnBreak()
15718 		<< Duration(stats.mean.lower_bound.count()) << ColumnBreak()
15719 		<< Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
15720 		<< Duration(stats.standardDeviation.point.count()) << ColumnBreak()
15721 		<< Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
15722 		<< Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
15723 }
15724 
benchmarkFailed(std::string const & error)15725 void ConsoleReporter::benchmarkFailed(std::string const& error) {
15726 	Colour colour(Colour::Red);
15727     (*m_tablePrinter)
15728         << "Benchmark failed (" << error << ")"
15729         << ColumnBreak() << RowBreak();
15730 }
15731 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
15732 
testCaseEnded(TestCaseStats const & _testCaseStats)15733 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
15734     m_tablePrinter->close();
15735     StreamingReporterBase::testCaseEnded(_testCaseStats);
15736     m_headerPrinted = false;
15737 }
testGroupEnded(TestGroupStats const & _testGroupStats)15738 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
15739     if (currentGroupInfo.used) {
15740         printSummaryDivider();
15741         stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
15742         printTotals(_testGroupStats.totals);
15743         stream << '\n' << std::endl;
15744     }
15745     StreamingReporterBase::testGroupEnded(_testGroupStats);
15746 }
testRunEnded(TestRunStats const & _testRunStats)15747 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
15748     printTotalsDivider(_testRunStats.totals);
15749     printTotals(_testRunStats.totals);
15750     stream << std::endl;
15751     StreamingReporterBase::testRunEnded(_testRunStats);
15752 }
testRunStarting(TestRunInfo const & _testInfo)15753 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
15754     StreamingReporterBase::testRunStarting(_testInfo);
15755     printTestFilters();
15756 }
15757 
lazyPrint()15758 void ConsoleReporter::lazyPrint() {
15759 
15760     m_tablePrinter->close();
15761     lazyPrintWithoutClosingBenchmarkTable();
15762 }
15763 
lazyPrintWithoutClosingBenchmarkTable()15764 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
15765 
15766     if (!currentTestRunInfo.used)
15767         lazyPrintRunInfo();
15768     if (!currentGroupInfo.used)
15769         lazyPrintGroupInfo();
15770 
15771     if (!m_headerPrinted) {
15772         printTestCaseAndSectionHeader();
15773         m_headerPrinted = true;
15774     }
15775 }
lazyPrintRunInfo()15776 void ConsoleReporter::lazyPrintRunInfo() {
15777     stream << '\n' << getLineOfChars<'~'>() << '\n';
15778     Colour colour(Colour::SecondaryText);
15779     stream << currentTestRunInfo->name
15780         << " is a Catch v" << libraryVersion() << " host application.\n"
15781         << "Run with -? for options\n\n";
15782 
15783     if (m_config->rngSeed() != 0)
15784         stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
15785 
15786     currentTestRunInfo.used = true;
15787 }
lazyPrintGroupInfo()15788 void ConsoleReporter::lazyPrintGroupInfo() {
15789     if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
15790         printClosedHeader("Group: " + currentGroupInfo->name);
15791         currentGroupInfo.used = true;
15792     }
15793 }
printTestCaseAndSectionHeader()15794 void ConsoleReporter::printTestCaseAndSectionHeader() {
15795     assert(!m_sectionStack.empty());
15796     printOpenHeader(currentTestCaseInfo->name);
15797 
15798     if (m_sectionStack.size() > 1) {
15799         Colour colourGuard(Colour::Headers);
15800 
15801         auto
15802             it = m_sectionStack.begin() + 1, // Skip first section (test case)
15803             itEnd = m_sectionStack.end();
15804         for (; it != itEnd; ++it)
15805             printHeaderString(it->name, 2);
15806     }
15807 
15808     SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
15809 
15810     if (!lineInfo.empty()) {
15811         stream << getLineOfChars<'-'>() << '\n';
15812         Colour colourGuard(Colour::FileName);
15813         stream << lineInfo << '\n';
15814     }
15815     stream << getLineOfChars<'.'>() << '\n' << std::endl;
15816 }
15817 
printClosedHeader(std::string const & _name)15818 void ConsoleReporter::printClosedHeader(std::string const& _name) {
15819     printOpenHeader(_name);
15820     stream << getLineOfChars<'.'>() << '\n';
15821 }
printOpenHeader(std::string const & _name)15822 void ConsoleReporter::printOpenHeader(std::string const& _name) {
15823     stream << getLineOfChars<'-'>() << '\n';
15824     {
15825         Colour colourGuard(Colour::Headers);
15826         printHeaderString(_name);
15827     }
15828 }
15829 
15830 // if string has a : in first line will set indent to follow it on
15831 // subsequent lines
printHeaderString(std::string const & _string,std::size_t indent)15832 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
15833     std::size_t i = _string.find(": ");
15834     if (i != std::string::npos)
15835         i += 2;
15836     else
15837         i = 0;
15838     stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
15839 }
15840 
15841 struct SummaryColumn {
15842 
SummaryColumnCatch::SummaryColumn15843     SummaryColumn( std::string _label, Colour::Code _colour )
15844     :   label( std::move( _label ) ),
15845         colour( _colour ) {}
addRowCatch::SummaryColumn15846     SummaryColumn addRow( std::size_t count ) {
15847         ReusableStringStream rss;
15848         rss << count;
15849         std::string row = rss.str();
15850         for (auto& oldRow : rows) {
15851             while (oldRow.size() < row.size())
15852                 oldRow = ' ' + oldRow;
15853             while (oldRow.size() > row.size())
15854                 row = ' ' + row;
15855         }
15856         rows.push_back(row);
15857         return *this;
15858     }
15859 
15860     std::string label;
15861     Colour::Code colour;
15862     std::vector<std::string> rows;
15863 
15864 };
15865 
printTotals(Totals const & totals)15866 void ConsoleReporter::printTotals( Totals const& totals ) {
15867     if (totals.testCases.total() == 0) {
15868         stream << Colour(Colour::Warning) << "No tests ran\n";
15869     } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
15870         stream << Colour(Colour::ResultSuccess) << "All tests passed";
15871         stream << " ("
15872             << pluralise(totals.assertions.passed, "assertion") << " in "
15873             << pluralise(totals.testCases.passed, "test case") << ')'
15874             << '\n';
15875     } else {
15876 
15877         std::vector<SummaryColumn> columns;
15878         columns.push_back(SummaryColumn("", Colour::None)
15879                           .addRow(totals.testCases.total())
15880                           .addRow(totals.assertions.total()));
15881         columns.push_back(SummaryColumn("passed", Colour::Success)
15882                           .addRow(totals.testCases.passed)
15883                           .addRow(totals.assertions.passed));
15884         columns.push_back(SummaryColumn("failed", Colour::ResultError)
15885                           .addRow(totals.testCases.failed)
15886                           .addRow(totals.assertions.failed));
15887         columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
15888                           .addRow(totals.testCases.failedButOk)
15889                           .addRow(totals.assertions.failedButOk));
15890 
15891         printSummaryRow("test cases", columns, 0);
15892         printSummaryRow("assertions", columns, 1);
15893     }
15894 }
printSummaryRow(std::string const & label,std::vector<SummaryColumn> const & cols,std::size_t row)15895 void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
15896     for (auto col : cols) {
15897         std::string value = col.rows[row];
15898         if (col.label.empty()) {
15899             stream << label << ": ";
15900             if (value != "0")
15901                 stream << value;
15902             else
15903                 stream << Colour(Colour::Warning) << "- none -";
15904         } else if (value != "0") {
15905             stream << Colour(Colour::LightGrey) << " | ";
15906             stream << Colour(col.colour)
15907                 << value << ' ' << col.label;
15908         }
15909     }
15910     stream << '\n';
15911 }
15912 
printTotalsDivider(Totals const & totals)15913 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
15914     if (totals.testCases.total() > 0) {
15915         std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
15916         std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
15917         std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
15918         while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
15919             findMax(failedRatio, failedButOkRatio, passedRatio)++;
15920         while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
15921             findMax(failedRatio, failedButOkRatio, passedRatio)--;
15922 
15923         stream << Colour(Colour::Error) << std::string(failedRatio, '=');
15924         stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
15925         if (totals.testCases.allPassed())
15926             stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
15927         else
15928             stream << Colour(Colour::Success) << std::string(passedRatio, '=');
15929     } else {
15930         stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
15931     }
15932     stream << '\n';
15933 }
printSummaryDivider()15934 void ConsoleReporter::printSummaryDivider() {
15935     stream << getLineOfChars<'-'>() << '\n';
15936 }
15937 
printTestFilters()15938 void ConsoleReporter::printTestFilters() {
15939     if (m_config->testSpec().hasFilters())
15940         stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
15941 }
15942 
15943 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
15944 
15945 } // end namespace Catch
15946 
15947 #if defined(_MSC_VER)
15948 #pragma warning(pop)
15949 #endif
15950 
15951 #if defined(__clang__)
15952 #  pragma clang diagnostic pop
15953 #endif
15954 // end catch_reporter_console.cpp
15955 // start catch_reporter_junit.cpp
15956 
15957 #include <cassert>
15958 #include <sstream>
15959 #include <ctime>
15960 #include <algorithm>
15961 
15962 namespace Catch {
15963 
15964     namespace {
getCurrentTimestamp()15965         std::string getCurrentTimestamp() {
15966             // Beware, this is not reentrant because of backward compatibility issues
15967             // Also, UTC only, again because of backward compatibility (%z is C++11)
15968             time_t rawtime;
15969             std::time(&rawtime);
15970             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
15971 
15972 #ifdef _MSC_VER
15973             std::tm timeInfo = {};
15974             gmtime_s(&timeInfo, &rawtime);
15975 #else
15976             std::tm* timeInfo;
15977             timeInfo = std::gmtime(&rawtime);
15978 #endif
15979 
15980             char timeStamp[timeStampSize];
15981             const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
15982 
15983 #ifdef _MSC_VER
15984             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
15985 #else
15986             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
15987 #endif
15988             return std::string(timeStamp);
15989         }
15990 
fileNameTag(const std::vector<std::string> & tags)15991         std::string fileNameTag(const std::vector<std::string> &tags) {
15992             auto it = std::find_if(begin(tags),
15993                                    end(tags),
15994                                    [] (std::string const& tag) {return tag.front() == '#'; });
15995             if (it != tags.end())
15996                 return it->substr(1);
15997             return std::string();
15998         }
15999     } // anonymous namespace
16000 
JunitReporter(ReporterConfig const & _config)16001     JunitReporter::JunitReporter( ReporterConfig const& _config )
16002         :   CumulativeReporterBase( _config ),
16003             xml( _config.stream() )
16004         {
16005             m_reporterPrefs.shouldRedirectStdOut = true;
16006             m_reporterPrefs.shouldReportAllAssertions = true;
16007         }
16008 
~JunitReporter()16009     JunitReporter::~JunitReporter() {}
16010 
getDescription()16011     std::string JunitReporter::getDescription() {
16012         return "Reports test results in an XML format that looks like Ant's junitreport target";
16013     }
16014 
noMatchingTestCases(std::string const &)16015     void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16016 
testRunStarting(TestRunInfo const & runInfo)16017     void JunitReporter::testRunStarting( TestRunInfo const& runInfo )  {
16018         CumulativeReporterBase::testRunStarting( runInfo );
16019         xml.startElement( "testsuites" );
16020     }
16021 
testGroupStarting(GroupInfo const & groupInfo)16022     void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16023         suiteTimer.start();
16024         stdOutForSuite.clear();
16025         stdErrForSuite.clear();
16026         unexpectedExceptions = 0;
16027         CumulativeReporterBase::testGroupStarting( groupInfo );
16028     }
16029 
testCaseStarting(TestCaseInfo const & testCaseInfo)16030     void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16031         m_okToFail = testCaseInfo.okToFail();
16032     }
16033 
assertionEnded(AssertionStats const & assertionStats)16034     bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16035         if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16036             unexpectedExceptions++;
16037         return CumulativeReporterBase::assertionEnded( assertionStats );
16038     }
16039 
testCaseEnded(TestCaseStats const & testCaseStats)16040     void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16041         stdOutForSuite += testCaseStats.stdOut;
16042         stdErrForSuite += testCaseStats.stdErr;
16043         CumulativeReporterBase::testCaseEnded( testCaseStats );
16044     }
16045 
testGroupEnded(TestGroupStats const & testGroupStats)16046     void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16047         double suiteTime = suiteTimer.getElapsedSeconds();
16048         CumulativeReporterBase::testGroupEnded( testGroupStats );
16049         writeGroup( *m_testGroups.back(), suiteTime );
16050     }
16051 
testRunEndedCumulative()16052     void JunitReporter::testRunEndedCumulative() {
16053         xml.endElement();
16054     }
16055 
writeGroup(TestGroupNode const & groupNode,double suiteTime)16056     void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16057         XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16058 
16059         TestGroupStats const& stats = groupNode.value;
16060         xml.writeAttribute( "name", stats.groupInfo.name );
16061         xml.writeAttribute( "errors", unexpectedExceptions );
16062         xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16063         xml.writeAttribute( "tests", stats.totals.assertions.total() );
16064         xml.writeAttribute( "hostname", "tbd" ); // !TBD
16065         if( m_config->showDurations() == ShowDurations::Never )
16066             xml.writeAttribute( "time", "" );
16067         else
16068             xml.writeAttribute( "time", suiteTime );
16069         xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16070 
16071         // Write properties if there are any
16072         if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16073             auto properties = xml.scopedElement("properties");
16074             if (m_config->hasTestFilters()) {
16075                 xml.scopedElement("property")
16076                     .writeAttribute("name", "filters")
16077                     .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16078             }
16079             if (m_config->rngSeed() != 0) {
16080                 xml.scopedElement("property")
16081                     .writeAttribute("name", "random-seed")
16082                     .writeAttribute("value", m_config->rngSeed());
16083             }
16084         }
16085 
16086         // Write test cases
16087         for( auto const& child : groupNode.children )
16088             writeTestCase( *child );
16089 
16090         xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
16091         xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
16092     }
16093 
writeTestCase(TestCaseNode const & testCaseNode)16094     void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16095         TestCaseStats const& stats = testCaseNode.value;
16096 
16097         // All test cases have exactly one section - which represents the
16098         // test case itself. That section may have 0-n nested sections
16099         assert( testCaseNode.children.size() == 1 );
16100         SectionNode const& rootSection = *testCaseNode.children.front();
16101 
16102         std::string className = stats.testInfo.className;
16103 
16104         if( className.empty() ) {
16105             className = fileNameTag(stats.testInfo.tags);
16106             if ( className.empty() )
16107                 className = "global";
16108         }
16109 
16110         if ( !m_config->name().empty() )
16111             className = m_config->name() + "." + className;
16112 
16113         writeSection( className, "", rootSection );
16114     }
16115 
writeSection(std::string const & className,std::string const & rootName,SectionNode const & sectionNode)16116     void JunitReporter::writeSection(  std::string const& className,
16117                         std::string const& rootName,
16118                         SectionNode const& sectionNode ) {
16119         std::string name = trim( sectionNode.stats.sectionInfo.name );
16120         if( !rootName.empty() )
16121             name = rootName + '/' + name;
16122 
16123         if( !sectionNode.assertions.empty() ||
16124             !sectionNode.stdOut.empty() ||
16125             !sectionNode.stdErr.empty() ) {
16126             XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16127             if( className.empty() ) {
16128                 xml.writeAttribute( "classname", name );
16129                 xml.writeAttribute( "name", "root" );
16130             }
16131             else {
16132                 xml.writeAttribute( "classname", className );
16133                 xml.writeAttribute( "name", name );
16134             }
16135             xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
16136 
16137             writeAssertions( sectionNode );
16138 
16139             if( !sectionNode.stdOut.empty() )
16140                 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
16141             if( !sectionNode.stdErr.empty() )
16142                 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
16143         }
16144         for( auto const& childNode : sectionNode.childSections )
16145             if( className.empty() )
16146                 writeSection( name, "", *childNode );
16147             else
16148                 writeSection( className, name, *childNode );
16149     }
16150 
writeAssertions(SectionNode const & sectionNode)16151     void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
16152         for( auto const& assertion : sectionNode.assertions )
16153             writeAssertion( assertion );
16154     }
16155 
writeAssertion(AssertionStats const & stats)16156     void JunitReporter::writeAssertion( AssertionStats const& stats ) {
16157         AssertionResult const& result = stats.assertionResult;
16158         if( !result.isOk() ) {
16159             std::string elementName;
16160             switch( result.getResultType() ) {
16161                 case ResultWas::ThrewException:
16162                 case ResultWas::FatalErrorCondition:
16163                     elementName = "error";
16164                     break;
16165                 case ResultWas::ExplicitFailure:
16166                     elementName = "failure";
16167                     break;
16168                 case ResultWas::ExpressionFailed:
16169                     elementName = "failure";
16170                     break;
16171                 case ResultWas::DidntThrowException:
16172                     elementName = "failure";
16173                     break;
16174 
16175                 // We should never see these here:
16176                 case ResultWas::Info:
16177                 case ResultWas::Warning:
16178                 case ResultWas::Ok:
16179                 case ResultWas::Unknown:
16180                 case ResultWas::FailureBit:
16181                 case ResultWas::Exception:
16182                     elementName = "internalError";
16183                     break;
16184             }
16185 
16186             XmlWriter::ScopedElement e = xml.scopedElement( elementName );
16187 
16188             xml.writeAttribute( "message", result.getExpandedExpression() );
16189             xml.writeAttribute( "type", result.getTestMacroName() );
16190 
16191             ReusableStringStream rss;
16192             if( !result.getMessage().empty() )
16193                 rss << result.getMessage() << '\n';
16194             for( auto const& msg : stats.infoMessages )
16195                 if( msg.type == ResultWas::Info )
16196                     rss << msg.message << '\n';
16197 
16198             rss << "at " << result.getSourceInfo();
16199             xml.writeText( rss.str(), false );
16200         }
16201     }
16202 
16203     CATCH_REGISTER_REPORTER( "junit", JunitReporter )
16204 
16205 } // end namespace Catch
16206 // end catch_reporter_junit.cpp
16207 // start catch_reporter_listening.cpp
16208 
16209 #include <cassert>
16210 
16211 namespace Catch {
16212 
ListeningReporter()16213     ListeningReporter::ListeningReporter() {
16214         // We will assume that listeners will always want all assertions
16215         m_preferences.shouldReportAllAssertions = true;
16216     }
16217 
addListener(IStreamingReporterPtr && listener)16218     void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
16219         m_listeners.push_back( std::move( listener ) );
16220     }
16221 
addReporter(IStreamingReporterPtr && reporter)16222     void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
16223         assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
16224         m_reporter = std::move( reporter );
16225         m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
16226     }
16227 
getPreferences() const16228     ReporterPreferences ListeningReporter::getPreferences() const {
16229         return m_preferences;
16230     }
16231 
getSupportedVerbosities()16232     std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
16233         return std::set<Verbosity>{ };
16234     }
16235 
noMatchingTestCases(std::string const & spec)16236     void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
16237         for ( auto const& listener : m_listeners ) {
16238             listener->noMatchingTestCases( spec );
16239         }
16240         m_reporter->noMatchingTestCases( spec );
16241     }
16242 
16243 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)16244     void ListeningReporter::benchmarkPreparing( std::string const& name ) {
16245 		for (auto const& listener : m_listeners) {
16246 			listener->benchmarkPreparing(name);
16247 		}
16248 		m_reporter->benchmarkPreparing(name);
16249 	}
benchmarkStarting(BenchmarkInfo const & benchmarkInfo)16250     void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
16251         for ( auto const& listener : m_listeners ) {
16252             listener->benchmarkStarting( benchmarkInfo );
16253         }
16254         m_reporter->benchmarkStarting( benchmarkInfo );
16255     }
benchmarkEnded(BenchmarkStats<> const & benchmarkStats)16256     void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
16257         for ( auto const& listener : m_listeners ) {
16258             listener->benchmarkEnded( benchmarkStats );
16259         }
16260         m_reporter->benchmarkEnded( benchmarkStats );
16261     }
16262 
benchmarkFailed(std::string const & error)16263 	void ListeningReporter::benchmarkFailed( std::string const& error ) {
16264 		for (auto const& listener : m_listeners) {
16265 			listener->benchmarkFailed(error);
16266 		}
16267 		m_reporter->benchmarkFailed(error);
16268 	}
16269 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16270 
testRunStarting(TestRunInfo const & testRunInfo)16271     void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
16272         for ( auto const& listener : m_listeners ) {
16273             listener->testRunStarting( testRunInfo );
16274         }
16275         m_reporter->testRunStarting( testRunInfo );
16276     }
16277 
testGroupStarting(GroupInfo const & groupInfo)16278     void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16279         for ( auto const& listener : m_listeners ) {
16280             listener->testGroupStarting( groupInfo );
16281         }
16282         m_reporter->testGroupStarting( groupInfo );
16283     }
16284 
testCaseStarting(TestCaseInfo const & testInfo)16285     void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
16286         for ( auto const& listener : m_listeners ) {
16287             listener->testCaseStarting( testInfo );
16288         }
16289         m_reporter->testCaseStarting( testInfo );
16290     }
16291 
sectionStarting(SectionInfo const & sectionInfo)16292     void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
16293         for ( auto const& listener : m_listeners ) {
16294             listener->sectionStarting( sectionInfo );
16295         }
16296         m_reporter->sectionStarting( sectionInfo );
16297     }
16298 
assertionStarting(AssertionInfo const & assertionInfo)16299     void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
16300         for ( auto const& listener : m_listeners ) {
16301             listener->assertionStarting( assertionInfo );
16302         }
16303         m_reporter->assertionStarting( assertionInfo );
16304     }
16305 
16306     // The return value indicates if the messages buffer should be cleared:
assertionEnded(AssertionStats const & assertionStats)16307     bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
16308         for( auto const& listener : m_listeners ) {
16309             static_cast<void>( listener->assertionEnded( assertionStats ) );
16310         }
16311         return m_reporter->assertionEnded( assertionStats );
16312     }
16313 
sectionEnded(SectionStats const & sectionStats)16314     void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
16315         for ( auto const& listener : m_listeners ) {
16316             listener->sectionEnded( sectionStats );
16317         }
16318         m_reporter->sectionEnded( sectionStats );
16319     }
16320 
testCaseEnded(TestCaseStats const & testCaseStats)16321     void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16322         for ( auto const& listener : m_listeners ) {
16323             listener->testCaseEnded( testCaseStats );
16324         }
16325         m_reporter->testCaseEnded( testCaseStats );
16326     }
16327 
testGroupEnded(TestGroupStats const & testGroupStats)16328     void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16329         for ( auto const& listener : m_listeners ) {
16330             listener->testGroupEnded( testGroupStats );
16331         }
16332         m_reporter->testGroupEnded( testGroupStats );
16333     }
16334 
testRunEnded(TestRunStats const & testRunStats)16335     void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
16336         for ( auto const& listener : m_listeners ) {
16337             listener->testRunEnded( testRunStats );
16338         }
16339         m_reporter->testRunEnded( testRunStats );
16340     }
16341 
skipTest(TestCaseInfo const & testInfo)16342     void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
16343         for ( auto const& listener : m_listeners ) {
16344             listener->skipTest( testInfo );
16345         }
16346         m_reporter->skipTest( testInfo );
16347     }
16348 
isMulti() const16349     bool ListeningReporter::isMulti() const {
16350         return true;
16351     }
16352 
16353 } // end namespace Catch
16354 // end catch_reporter_listening.cpp
16355 // start catch_reporter_xml.cpp
16356 
16357 #if defined(_MSC_VER)
16358 #pragma warning(push)
16359 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16360                               // Note that 4062 (not all labels are handled
16361                               // and default is missing) is enabled
16362 #endif
16363 
16364 namespace Catch {
XmlReporter(ReporterConfig const & _config)16365     XmlReporter::XmlReporter( ReporterConfig const& _config )
16366     :   StreamingReporterBase( _config ),
16367         m_xml(_config.stream())
16368     {
16369         m_reporterPrefs.shouldRedirectStdOut = true;
16370         m_reporterPrefs.shouldReportAllAssertions = true;
16371     }
16372 
16373     XmlReporter::~XmlReporter() = default;
16374 
getDescription()16375     std::string XmlReporter::getDescription() {
16376         return "Reports test results as an XML document";
16377     }
16378 
getStylesheetRef() const16379     std::string XmlReporter::getStylesheetRef() const {
16380         return std::string();
16381     }
16382 
writeSourceInfo(SourceLineInfo const & sourceInfo)16383     void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
16384         m_xml
16385             .writeAttribute( "filename", sourceInfo.file )
16386             .writeAttribute( "line", sourceInfo.line );
16387     }
16388 
noMatchingTestCases(std::string const & s)16389     void XmlReporter::noMatchingTestCases( std::string const& s ) {
16390         StreamingReporterBase::noMatchingTestCases( s );
16391     }
16392 
testRunStarting(TestRunInfo const & testInfo)16393     void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
16394         StreamingReporterBase::testRunStarting( testInfo );
16395         std::string stylesheetRef = getStylesheetRef();
16396         if( !stylesheetRef.empty() )
16397             m_xml.writeStylesheetRef( stylesheetRef );
16398         m_xml.startElement( "Catch" );
16399         if( !m_config->name().empty() )
16400             m_xml.writeAttribute( "name", m_config->name() );
16401         if (m_config->testSpec().hasFilters())
16402             m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
16403         if( m_config->rngSeed() != 0 )
16404             m_xml.scopedElement( "Randomness" )
16405                 .writeAttribute( "seed", m_config->rngSeed() );
16406     }
16407 
testGroupStarting(GroupInfo const & groupInfo)16408     void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16409         StreamingReporterBase::testGroupStarting( groupInfo );
16410         m_xml.startElement( "Group" )
16411             .writeAttribute( "name", groupInfo.name );
16412     }
16413 
testCaseStarting(TestCaseInfo const & testInfo)16414     void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
16415         StreamingReporterBase::testCaseStarting(testInfo);
16416         m_xml.startElement( "TestCase" )
16417             .writeAttribute( "name", trim( testInfo.name ) )
16418             .writeAttribute( "description", testInfo.description )
16419             .writeAttribute( "tags", testInfo.tagsAsString() );
16420 
16421         writeSourceInfo( testInfo.lineInfo );
16422 
16423         if ( m_config->showDurations() == ShowDurations::Always )
16424             m_testCaseTimer.start();
16425         m_xml.ensureTagClosed();
16426     }
16427 
sectionStarting(SectionInfo const & sectionInfo)16428     void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
16429         StreamingReporterBase::sectionStarting( sectionInfo );
16430         if( m_sectionDepth++ > 0 ) {
16431             m_xml.startElement( "Section" )
16432                 .writeAttribute( "name", trim( sectionInfo.name ) );
16433             writeSourceInfo( sectionInfo.lineInfo );
16434             m_xml.ensureTagClosed();
16435         }
16436     }
16437 
assertionStarting(AssertionInfo const &)16438     void XmlReporter::assertionStarting( AssertionInfo const& ) { }
16439 
assertionEnded(AssertionStats const & assertionStats)16440     bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
16441 
16442         AssertionResult const& result = assertionStats.assertionResult;
16443 
16444         bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16445 
16446         if( includeResults || result.getResultType() == ResultWas::Warning ) {
16447             // Print any info messages in <Info> tags.
16448             for( auto const& msg : assertionStats.infoMessages ) {
16449                 if( msg.type == ResultWas::Info && includeResults ) {
16450                     m_xml.scopedElement( "Info" )
16451                             .writeText( msg.message );
16452                 } else if ( msg.type == ResultWas::Warning ) {
16453                     m_xml.scopedElement( "Warning" )
16454                             .writeText( msg.message );
16455                 }
16456             }
16457         }
16458 
16459         // Drop out if result was successful but we're not printing them.
16460         if( !includeResults && result.getResultType() != ResultWas::Warning )
16461             return true;
16462 
16463         // Print the expression if there is one.
16464         if( result.hasExpression() ) {
16465             m_xml.startElement( "Expression" )
16466                 .writeAttribute( "success", result.succeeded() )
16467                 .writeAttribute( "type", result.getTestMacroName() );
16468 
16469             writeSourceInfo( result.getSourceInfo() );
16470 
16471             m_xml.scopedElement( "Original" )
16472                 .writeText( result.getExpression() );
16473             m_xml.scopedElement( "Expanded" )
16474                 .writeText( result.getExpandedExpression() );
16475         }
16476 
16477         // And... Print a result applicable to each result type.
16478         switch( result.getResultType() ) {
16479             case ResultWas::ThrewException:
16480                 m_xml.startElement( "Exception" );
16481                 writeSourceInfo( result.getSourceInfo() );
16482                 m_xml.writeText( result.getMessage() );
16483                 m_xml.endElement();
16484                 break;
16485             case ResultWas::FatalErrorCondition:
16486                 m_xml.startElement( "FatalErrorCondition" );
16487                 writeSourceInfo( result.getSourceInfo() );
16488                 m_xml.writeText( result.getMessage() );
16489                 m_xml.endElement();
16490                 break;
16491             case ResultWas::Info:
16492                 m_xml.scopedElement( "Info" )
16493                     .writeText( result.getMessage() );
16494                 break;
16495             case ResultWas::Warning:
16496                 // Warning will already have been written
16497                 break;
16498             case ResultWas::ExplicitFailure:
16499                 m_xml.startElement( "Failure" );
16500                 writeSourceInfo( result.getSourceInfo() );
16501                 m_xml.writeText( result.getMessage() );
16502                 m_xml.endElement();
16503                 break;
16504             default:
16505                 break;
16506         }
16507 
16508         if( result.hasExpression() )
16509             m_xml.endElement();
16510 
16511         return true;
16512     }
16513 
sectionEnded(SectionStats const & sectionStats)16514     void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
16515         StreamingReporterBase::sectionEnded( sectionStats );
16516         if( --m_sectionDepth > 0 ) {
16517             XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
16518             e.writeAttribute( "successes", sectionStats.assertions.passed );
16519             e.writeAttribute( "failures", sectionStats.assertions.failed );
16520             e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
16521 
16522             if ( m_config->showDurations() == ShowDurations::Always )
16523                 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
16524 
16525             m_xml.endElement();
16526         }
16527     }
16528 
testCaseEnded(TestCaseStats const & testCaseStats)16529     void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16530         StreamingReporterBase::testCaseEnded( testCaseStats );
16531         XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
16532         e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
16533 
16534         if ( m_config->showDurations() == ShowDurations::Always )
16535             e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
16536 
16537         if( !testCaseStats.stdOut.empty() )
16538             m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
16539         if( !testCaseStats.stdErr.empty() )
16540             m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
16541 
16542         m_xml.endElement();
16543     }
16544 
testGroupEnded(TestGroupStats const & testGroupStats)16545     void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16546         StreamingReporterBase::testGroupEnded( testGroupStats );
16547         // TODO: Check testGroupStats.aborting and act accordingly.
16548         m_xml.scopedElement( "OverallResults" )
16549             .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
16550             .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
16551             .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
16552         m_xml.endElement();
16553     }
16554 
testRunEnded(TestRunStats const & testRunStats)16555     void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
16556         StreamingReporterBase::testRunEnded( testRunStats );
16557         m_xml.scopedElement( "OverallResults" )
16558             .writeAttribute( "successes", testRunStats.totals.assertions.passed )
16559             .writeAttribute( "failures", testRunStats.totals.assertions.failed )
16560             .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
16561         m_xml.endElement();
16562     }
16563 
16564 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)16565     void XmlReporter::benchmarkPreparing(std::string const& name) {
16566         m_xml.startElement("BenchmarkResults")
16567             .writeAttribute("name", name);
16568     }
16569 
benchmarkStarting(BenchmarkInfo const & info)16570     void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
16571         m_xml.writeAttribute("samples", info.samples)
16572             .writeAttribute("resamples", info.resamples)
16573             .writeAttribute("iterations", info.iterations)
16574             .writeAttribute("clockResolution", static_cast<uint64_t>(info.clockResolution))
16575             .writeAttribute("estimatedDuration", static_cast<uint64_t>(info.estimatedDuration))
16576             .writeComment("All values in nano seconds");
16577     }
16578 
benchmarkEnded(BenchmarkStats<> const & benchmarkStats)16579     void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
16580         m_xml.startElement("mean")
16581             .writeAttribute("value", static_cast<uint64_t>(benchmarkStats.mean.point.count()))
16582             .writeAttribute("lowerBound", static_cast<uint64_t>(benchmarkStats.mean.lower_bound.count()))
16583             .writeAttribute("upperBound", static_cast<uint64_t>(benchmarkStats.mean.upper_bound.count()))
16584             .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
16585         m_xml.endElement();
16586         m_xml.startElement("standardDeviation")
16587             .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
16588             .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
16589             .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
16590             .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
16591         m_xml.endElement();
16592         m_xml.startElement("outliers")
16593             .writeAttribute("variance", benchmarkStats.outlierVariance)
16594             .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
16595             .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
16596             .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
16597             .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
16598         m_xml.endElement();
16599         m_xml.endElement();
16600     }
16601 
benchmarkFailed(std::string const & error)16602     void XmlReporter::benchmarkFailed(std::string const &error) {
16603         m_xml.scopedElement("failed").
16604             writeAttribute("message", error);
16605         m_xml.endElement();
16606     }
16607 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16608 
16609     CATCH_REGISTER_REPORTER( "xml", XmlReporter )
16610 
16611 } // end namespace Catch
16612 
16613 #if defined(_MSC_VER)
16614 #pragma warning(pop)
16615 #endif
16616 // end catch_reporter_xml.cpp
16617 
16618 namespace Catch {
16619     LeakDetector leakDetector;
16620 }
16621 
16622 #ifdef __clang__
16623 #pragma clang diagnostic pop
16624 #endif
16625 
16626 // end catch_impl.hpp
16627 #endif
16628 
16629 #ifdef CATCH_CONFIG_MAIN
16630 // start catch_default_main.hpp
16631 
16632 #ifndef __OBJC__
16633 
16634 #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
16635 // Standard C/C++ Win32 Unicode wmain entry point
wmain(int argc,wchar_t * argv[],wchar_t * [])16636 extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
16637 #else
16638 // Standard C/C++ main entry point
16639 int main (int argc, char * argv[]) {
16640 #endif
16641 
16642     return Catch::Session().run( argc, argv );
16643 }
16644 
16645 #else // __OBJC__
16646 
16647 // Objective-C entry point
16648 int main (int argc, char * const argv[]) {
16649 #if !CATCH_ARC_ENABLED
16650     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
16651 #endif
16652 
16653     Catch::registerTestMethods();
16654     int result = Catch::Session().run( argc, (char**)argv );
16655 
16656 #if !CATCH_ARC_ENABLED
16657     [pool drain];
16658 #endif
16659 
16660     return result;
16661 }
16662 
16663 #endif // __OBJC__
16664 
16665 // end catch_default_main.hpp
16666 #endif
16667 
16668 #if !defined(CATCH_CONFIG_IMPL_ONLY)
16669 
16670 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
16671 #  undef CLARA_CONFIG_MAIN
16672 #endif
16673 
16674 #if !defined(CATCH_CONFIG_DISABLE)
16675 //////
16676 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
16677 #ifdef CATCH_CONFIG_PREFIX_ALL
16678 
16679 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
16680 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
16681 
16682 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
16683 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
16684 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
16685 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16686 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
16687 #endif// CATCH_CONFIG_DISABLE_MATCHERS
16688 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
16689 
16690 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16691 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
16692 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16693 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16694 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
16695 
16696 #define CATCH_CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16697 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
16698 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
16699 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16700 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
16701 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16702 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16703 
16704 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16705 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
16706 
16707 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
16708 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16709 
16710 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
16711 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
16712 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
16713 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
16714 
16715 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
16716 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
16717 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
16718 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
16719 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
16720 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
16721 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
16722 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16723 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16724 
16725 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
16726 
16727 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
16728 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16729 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
16730 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16731 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
16732 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
16733 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
16734 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
16735 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
16736 #else
16737 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
16738 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
16739 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
16740 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
16741 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
16742 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
16743 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
16744 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
16745 #endif
16746 
16747 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
16748 #define CATCH_STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__ ,      #__VA_ARGS__ );     CATCH_SUCCEED( #__VA_ARGS__ )
16749 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
16750 #else
16751 #define CATCH_STATIC_REQUIRE( ... )       CATCH_REQUIRE( __VA_ARGS__ )
16752 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
16753 #endif
16754 
16755 // "BDD-style" convenience wrappers
16756 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
16757 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
16758 #define CATCH_GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( "    Given: " << desc )
16759 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
16760 #define CATCH_WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     When: " << desc )
16761 #define CATCH_AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
16762 #define CATCH_THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     Then: " << desc )
16763 #define CATCH_AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( "      And: " << desc )
16764 
16765 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16766 #define CATCH_BENCHMARK(...) \
16767     INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
16768 #define CATCH_BENCHMARK_ADVANCED(name) \
16769     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
16770 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16771 
16772 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
16773 #else
16774 
16775 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__  )
16776 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
16777 
16778 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
16779 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
16780 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
16781 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16782 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
16783 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16784 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
16785 
16786 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16787 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
16788 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16789 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16790 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
16791 
16792 #define CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16793 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
16794 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
16795 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16796 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
16797 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16798 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16799 
16800 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16801 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
16802 
16803 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
16804 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16805 
16806 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
16807 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
16808 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
16809 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
16810 
16811 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
16812 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
16813 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
16814 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
16815 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
16816 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
16817 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
16818 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16819 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
16820 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
16821 
16822 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
16823 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16824 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
16825 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16826 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
16827 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
16828 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
16829 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
16830 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
16831 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
16832 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
16833 #else
16834 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
16835 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
16836 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
16837 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
16838 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
16839 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
16840 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
16841 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
16842 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
16843 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
16844 #endif
16845 
16846 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
16847 #define STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__,  #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
16848 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
16849 #else
16850 #define STATIC_REQUIRE( ... )       REQUIRE( __VA_ARGS__ )
16851 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
16852 #endif
16853 
16854 #endif
16855 
16856 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
16857 
16858 // "BDD-style" convenience wrappers
16859 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
16860 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
16861 
16862 #define GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( "    Given: " << desc )
16863 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
16864 #define WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     When: " << desc )
16865 #define AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
16866 #define THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     Then: " << desc )
16867 #define AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( "      And: " << desc )
16868 
16869 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16870 #define BENCHMARK(...) \
16871     INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
16872 #define BENCHMARK_ADVANCED(name) \
16873     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
16874 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16875 
16876 using Catch::Detail::Approx;
16877 
16878 #else // CATCH_CONFIG_DISABLE
16879 
16880 //////
16881 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
16882 #ifdef CATCH_CONFIG_PREFIX_ALL
16883 
16884 #define CATCH_REQUIRE( ... )        (void)(0)
16885 #define CATCH_REQUIRE_FALSE( ... )  (void)(0)
16886 
16887 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
16888 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
16889 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher )     (void)(0)
16890 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16891 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
16892 #endif// CATCH_CONFIG_DISABLE_MATCHERS
16893 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
16894 
16895 #define CATCH_CHECK( ... )         (void)(0)
16896 #define CATCH_CHECK_FALSE( ... )   (void)(0)
16897 #define CATCH_CHECKED_IF( ... )    if (__VA_ARGS__)
16898 #define CATCH_CHECKED_ELSE( ... )  if (!(__VA_ARGS__))
16899 #define CATCH_CHECK_NOFAIL( ... )  (void)(0)
16900 
16901 #define CATCH_CHECK_THROWS( ... )  (void)(0)
16902 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
16903 #define CATCH_CHECK_THROWS_WITH( expr, matcher )     (void)(0)
16904 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16905 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
16906 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16907 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
16908 
16909 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16910 #define CATCH_CHECK_THAT( arg, matcher )   (void)(0)
16911 
16912 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
16913 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16914 
16915 #define CATCH_INFO( msg )          (void)(0)
16916 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
16917 #define CATCH_WARN( msg )          (void)(0)
16918 #define CATCH_CAPTURE( msg )       (void)(0)
16919 
16920 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
16921 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
16922 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
16923 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
16924 #define CATCH_SECTION( ... )
16925 #define CATCH_DYNAMIC_SECTION( ... )
16926 #define CATCH_FAIL( ... ) (void)(0)
16927 #define CATCH_FAIL_CHECK( ... ) (void)(0)
16928 #define CATCH_SUCCEED( ... ) (void)(0)
16929 
16930 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
16931 
16932 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
16933 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
16934 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
16935 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
16936 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
16937 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16938 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16939 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16940 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16941 #else
16942 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
16943 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
16944 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
16945 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
16946 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16947 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
16948 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16949 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
16950 #endif
16951 
16952 // "BDD-style" convenience wrappers
16953 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
16954 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
16955 #define CATCH_GIVEN( desc )
16956 #define CATCH_AND_GIVEN( desc )
16957 #define CATCH_WHEN( desc )
16958 #define CATCH_AND_WHEN( desc )
16959 #define CATCH_THEN( desc )
16960 #define CATCH_AND_THEN( desc )
16961 
16962 #define CATCH_STATIC_REQUIRE( ... )       (void)(0)
16963 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
16964 
16965 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
16966 #else
16967 
16968 #define REQUIRE( ... )       (void)(0)
16969 #define REQUIRE_FALSE( ... ) (void)(0)
16970 
16971 #define REQUIRE_THROWS( ... ) (void)(0)
16972 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
16973 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
16974 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16975 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
16976 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16977 #define REQUIRE_NOTHROW( ... ) (void)(0)
16978 
16979 #define CHECK( ... ) (void)(0)
16980 #define CHECK_FALSE( ... ) (void)(0)
16981 #define CHECKED_IF( ... ) if (__VA_ARGS__)
16982 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
16983 #define CHECK_NOFAIL( ... ) (void)(0)
16984 
16985 #define CHECK_THROWS( ... )  (void)(0)
16986 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
16987 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
16988 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16989 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
16990 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16991 #define CHECK_NOTHROW( ... ) (void)(0)
16992 
16993 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
16994 #define CHECK_THAT( arg, matcher ) (void)(0)
16995 
16996 #define REQUIRE_THAT( arg, matcher ) (void)(0)
16997 #endif // CATCH_CONFIG_DISABLE_MATCHERS
16998 
16999 #define INFO( msg ) (void)(0)
17000 #define UNSCOPED_INFO( msg ) (void)(0)
17001 #define WARN( msg ) (void)(0)
17002 #define CAPTURE( msg ) (void)(0)
17003 
17004 #define TEST_CASE( ... )  INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17005 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17006 #define METHOD_AS_TEST_CASE( method, ... )
17007 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17008 #define SECTION( ... )
17009 #define DYNAMIC_SECTION( ... )
17010 #define FAIL( ... ) (void)(0)
17011 #define FAIL_CHECK( ... ) (void)(0)
17012 #define SUCCEED( ... ) (void)(0)
17013 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17014 
17015 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17016 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17017 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17018 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17019 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17020 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17021 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17022 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17023 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17024 #else
17025 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17026 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17027 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17028 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17029 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17030 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17031 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17032 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17033 #endif
17034 
17035 #define STATIC_REQUIRE( ... )       (void)(0)
17036 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17037 
17038 #endif
17039 
17040 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17041 
17042 // "BDD-style" convenience wrappers
17043 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17044 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17045 
17046 #define GIVEN( desc )
17047 #define AND_GIVEN( desc )
17048 #define WHEN( desc )
17049 #define AND_WHEN( desc )
17050 #define THEN( desc )
17051 #define AND_THEN( desc )
17052 
17053 using Catch::Detail::Approx;
17054 
17055 #endif
17056 
17057 #endif // ! CATCH_CONFIG_IMPL_ONLY
17058 
17059 // start catch_reenable_warnings.h
17060 
17061 
17062 #ifdef __clang__
17063 #    ifdef __ICC // icpc defines the __clang__ macro
17064 #        pragma warning(pop)
17065 #    else
17066 #        pragma clang diagnostic pop
17067 #    endif
17068 #elif defined __GNUC__
17069 #    pragma GCC diagnostic pop
17070 #endif
17071 
17072 // end catch_reenable_warnings.h
17073 // end catch.hpp
17074 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
17075 
17076