1 /*
2  *  Catch v2.13.3
3  *  Generated: 2020-10-31 18:20:31.045274
4  *  ----------------------------------------------------------
5  *  This file has been merged from multiple headers. Please don't edit it directly
6  *  Copyright (c) 2020 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 13
18 #define CATCH_VERSION_PATCH 3
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 // We have to avoid both ICC and Clang, because they try to mask themselves
136 // as gcc, and we want only GCC in this block
137 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__)
138 #    define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
139 #    define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  _Pragma( "GCC diagnostic pop" )
140 
141 #    define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
142 
143 #endif
144 
145 #if defined(__clang__)
146 
147 #    define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
148 #    define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  _Pragma( "clang diagnostic pop" )
149 
150 // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
151 // which results in calls to destructors being emitted for each temporary,
152 // without a matching initialization. In practice, this can result in something
153 // like `std::string::~string` being called on an uninitialized value.
154 //
155 // For example, this code will likely segfault under IBM XL:
156 // ```
157 // REQUIRE(std::string("12") + "34" == "1234")
158 // ```
159 //
160 // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
161 #  if !defined(__ibmxl__) && !defined(__CUDACC__)
162 #    define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
163 #  endif
164 
165 #    define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
166          _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
167          _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
168 
169 #    define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
170          _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
171 
172 #    define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
173          _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
174 
175 #    define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
176          _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
177 
178 #    define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
179          _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
180 
181 #endif // __clang__
182 
183 ////////////////////////////////////////////////////////////////////////////////
184 // Assume that non-Windows platforms support posix signals by default
185 #if !defined(CATCH_PLATFORM_WINDOWS)
186     #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
187 #endif
188 
189 ////////////////////////////////////////////////////////////////////////////////
190 // We know some environments not to support full POSIX signals
191 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
192     #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
193 #endif
194 
195 #ifdef __OS400__
196 #       define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
197 #       define CATCH_CONFIG_COLOUR_NONE
198 #endif
199 
200 ////////////////////////////////////////////////////////////////////////////////
201 // Android somehow still does not support std::to_string
202 #if defined(__ANDROID__)
203 #    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
204 #    define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
205 #endif
206 
207 ////////////////////////////////////////////////////////////////////////////////
208 // Not all Windows environments support SEH properly
209 #if defined(__MINGW32__)
210 #    define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
211 #endif
212 
213 ////////////////////////////////////////////////////////////////////////////////
214 // PS4
215 #if defined(__ORBIS__)
216 #    define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
217 #endif
218 
219 ////////////////////////////////////////////////////////////////////////////////
220 // Cygwin
221 #ifdef __CYGWIN__
222 
223 // Required for some versions of Cygwin to declare gettimeofday
224 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
225 #   define _BSD_SOURCE
226 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
227 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
228 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
229            && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
230 
231 #    define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
232 
233 # endif
234 #endif // __CYGWIN__
235 
236 ////////////////////////////////////////////////////////////////////////////////
237 // Visual C++
238 #if defined(_MSC_VER)
239 
240 #  define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
241 #  define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION  __pragma( warning(pop) )
242 
243 // Universal Windows platform does not support SEH
244 // Or console colours (or console at all...)
245 #  if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
246 #    define CATCH_CONFIG_COLOUR_NONE
247 #  else
248 #    define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
249 #  endif
250 
251 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
252 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
253 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
254 #  if !defined(__clang__) // Handle Clang masquerading for msvc
255 #    if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
256 #      define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
257 #    endif // MSVC_TRADITIONAL
258 #  endif // __clang__
259 
260 #endif // _MSC_VER
261 
262 #if defined(_REENTRANT) || defined(_MSC_VER)
263 // Enable async processing, as -pthread is specified or no additional linking is required
264 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
265 #endif // _MSC_VER
266 
267 ////////////////////////////////////////////////////////////////////////////////
268 // Check if we are compiled with -fno-exceptions or equivalent
269 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
270 #  define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
271 #endif
272 
273 ////////////////////////////////////////////////////////////////////////////////
274 // DJGPP
275 #ifdef __DJGPP__
276 #  define CATCH_INTERNAL_CONFIG_NO_WCHAR
277 #endif // __DJGPP__
278 
279 ////////////////////////////////////////////////////////////////////////////////
280 // Embarcadero C++Build
281 #if defined(__BORLANDC__)
282     #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
283 #endif
284 
285 ////////////////////////////////////////////////////////////////////////////////
286 
287 // Use of __COUNTER__ is suppressed during code analysis in
288 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
289 // handled by it.
290 // Otherwise all supported compilers support COUNTER macro,
291 // but user still might want to turn it off
292 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
293     #define CATCH_INTERNAL_CONFIG_COUNTER
294 #endif
295 
296 ////////////////////////////////////////////////////////////////////////////////
297 
298 // RTX is a special version of Windows that is real time.
299 // This means that it is detected as Windows, but does not provide
300 // the same set of capabilities as real Windows does.
301 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
302     #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
303     #define CATCH_INTERNAL_CONFIG_NO_ASYNC
304     #define CATCH_CONFIG_COLOUR_NONE
305 #endif
306 
307 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
308 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
309 #endif
310 
311 // Various stdlib support checks that require __has_include
312 #if defined(__has_include)
313   // Check if string_view is available and usable
314   #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
315   #    define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
316   #endif
317 
318   // Check if optional is available and usable
319   #  if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
320   #    define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
321   #  endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
322 
323   // Check if byte is available and usable
324   #  if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
325   #    include <cstddef>
326   #    if __cpp_lib_byte > 0
327   #      define CATCH_INTERNAL_CONFIG_CPP17_BYTE
328   #    endif
329   #  endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
330 
331   // Check if variant is available and usable
332   #  if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
333   #    if defined(__clang__) && (__clang_major__ < 8)
334          // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
335          // fix should be in clang 8, workaround in libstdc++ 8.2
336   #      include <ciso646>
337   #      if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
338   #        define CATCH_CONFIG_NO_CPP17_VARIANT
339   #      else
340   #        define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
341   #      endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
342   #    else
343   #      define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
344   #    endif // defined(__clang__) && (__clang_major__ < 8)
345   #  endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
346 #endif // defined(__has_include)
347 
348 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
349 #   define CATCH_CONFIG_COUNTER
350 #endif
351 #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)
352 #   define CATCH_CONFIG_WINDOWS_SEH
353 #endif
354 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
355 #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)
356 #   define CATCH_CONFIG_POSIX_SIGNALS
357 #endif
358 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
359 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
360 #   define CATCH_CONFIG_WCHAR
361 #endif
362 
363 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
364 #    define CATCH_CONFIG_CPP11_TO_STRING
365 #endif
366 
367 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
368 #  define CATCH_CONFIG_CPP17_OPTIONAL
369 #endif
370 
371 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
372 #  define CATCH_CONFIG_CPP17_STRING_VIEW
373 #endif
374 
375 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
376 #  define CATCH_CONFIG_CPP17_VARIANT
377 #endif
378 
379 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
380 #  define CATCH_CONFIG_CPP17_BYTE
381 #endif
382 
383 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
384 #  define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
385 #endif
386 
387 #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)
388 #  define CATCH_CONFIG_NEW_CAPTURE
389 #endif
390 
391 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
392 #  define CATCH_CONFIG_DISABLE_EXCEPTIONS
393 #endif
394 
395 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
396 #  define CATCH_CONFIG_POLYFILL_ISNAN
397 #endif
398 
399 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC)  && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
400 #  define CATCH_CONFIG_USE_ASYNC
401 #endif
402 
403 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
404 #  define CATCH_CONFIG_ANDROID_LOGWRITE
405 #endif
406 
407 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
408 #  define CATCH_CONFIG_GLOBAL_NEXTAFTER
409 #endif
410 
411 // Even if we do not think the compiler has that warning, we still have
412 // to provide a macro that can be used by the code.
413 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
414 #   define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
415 #endif
416 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
417 #   define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
418 #endif
419 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
420 #   define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
421 #endif
422 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
423 #   define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
424 #endif
425 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
426 #   define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
427 #endif
428 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
429 #   define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
430 #endif
431 
432 // The goal of this macro is to avoid evaluation of the arguments, but
433 // still have the compiler warn on problems inside...
434 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
435 #   define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
436 #endif
437 
438 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
439 #   undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
440 #elif defined(__clang__) && (__clang_major__ < 5)
441 #   undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
442 #endif
443 
444 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
445 #   define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
446 #endif
447 
448 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
449 #define CATCH_TRY if ((true))
450 #define CATCH_CATCH_ALL if ((false))
451 #define CATCH_CATCH_ANON(type) if ((false))
452 #else
453 #define CATCH_TRY try
454 #define CATCH_CATCH_ALL catch (...)
455 #define CATCH_CATCH_ANON(type) catch (type)
456 #endif
457 
458 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
459 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
460 #endif
461 
462 // end catch_compiler_capabilities.h
463 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
464 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
465 #ifdef CATCH_CONFIG_COUNTER
466 #  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
467 #else
468 #  define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
469 #endif
470 
471 #include <iosfwd>
472 #include <string>
473 #include <cstdint>
474 
475 // We need a dummy global operator<< so we can bring it into Catch namespace later
476 struct Catch_global_namespace_dummy {};
477 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
478 
479 namespace Catch {
480 
481     struct CaseSensitive { enum Choice {
482         Yes,
483         No
484     }; };
485 
486     class NonCopyable {
487         NonCopyable( NonCopyable const& )              = delete;
488         NonCopyable( NonCopyable && )                  = delete;
489         NonCopyable& operator = ( NonCopyable const& ) = delete;
490         NonCopyable& operator = ( NonCopyable && )     = delete;
491 
492     protected:
493         NonCopyable();
494         virtual ~NonCopyable();
495     };
496 
497     struct SourceLineInfo {
498 
499         SourceLineInfo() = delete;
SourceLineInfoCatch::SourceLineInfo500         SourceLineInfo( char const* _file, std::size_t _line ) noexcept
501         :   file( _file ),
502             line( _line )
503         {}
504 
505         SourceLineInfo( SourceLineInfo const& other )            = default;
506         SourceLineInfo& operator = ( SourceLineInfo const& )     = default;
507         SourceLineInfo( SourceLineInfo&& )              noexcept = default;
508         SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
509 
emptyCatch::SourceLineInfo510         bool empty() const noexcept { return file[0] == '\0'; }
511         bool operator == ( SourceLineInfo const& other ) const noexcept;
512         bool operator < ( SourceLineInfo const& other ) const noexcept;
513 
514         char const* file;
515         std::size_t line;
516     };
517 
518     std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
519 
520     // Bring in operator<< from global namespace into Catch namespace
521     // This is necessary because the overload of operator<< above makes
522     // lookup stop at namespace Catch
523     using ::operator<<;
524 
525     // Use this in variadic streaming macros to allow
526     //    >> +StreamEndStop
527     // as well as
528     //    >> stuff +StreamEndStop
529     struct StreamEndStop {
530         std::string operator+() const;
531     };
532     template<typename T>
operator +(T const & value,StreamEndStop)533     T const& operator + ( T const& value, StreamEndStop ) {
534         return value;
535     }
536 }
537 
538 #define CATCH_INTERNAL_LINEINFO \
539     ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
540 
541 // end catch_common.h
542 namespace Catch {
543 
544     struct RegistrarForTagAliases {
545         RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
546     };
547 
548 } // end namespace Catch
549 
550 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
551     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
552     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
553     namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
554     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
555 
556 // end catch_tag_alias_autoregistrar.h
557 // start catch_test_registry.h
558 
559 // start catch_interfaces_testcase.h
560 
561 #include <vector>
562 
563 namespace Catch {
564 
565     class TestSpec;
566 
567     struct ITestInvoker {
568         virtual void invoke () const = 0;
569         virtual ~ITestInvoker();
570     };
571 
572     class TestCase;
573     struct IConfig;
574 
575     struct ITestCaseRegistry {
576         virtual ~ITestCaseRegistry();
577         virtual std::vector<TestCase> const& getAllTests() const = 0;
578         virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
579     };
580 
581     bool isThrowSafe( TestCase const& testCase, IConfig const& config );
582     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
583     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
584     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
585 
586 }
587 
588 // end catch_interfaces_testcase.h
589 // start catch_stringref.h
590 
591 #include <cstddef>
592 #include <string>
593 #include <iosfwd>
594 #include <cassert>
595 
596 namespace Catch {
597 
598     /// A non-owning string class (similar to the forthcoming std::string_view)
599     /// Note that, because a StringRef may be a substring of another string,
600     /// it may not be null terminated.
601     class StringRef {
602     public:
603         using size_type = std::size_t;
604         using const_iterator = const char*;
605 
606     private:
607         static constexpr char const* const s_empty = "";
608 
609         char const* m_start = s_empty;
610         size_type m_size = 0;
611 
612     public: // construction
613         constexpr StringRef() noexcept = default;
614 
615         StringRef( char const* rawChars ) noexcept;
616 
StringRef(char const * rawChars,size_type size)617         constexpr StringRef( char const* rawChars, size_type size ) noexcept
618         :   m_start( rawChars ),
619             m_size( size )
620         {}
621 
StringRef(std::string const & stdString)622         StringRef( std::string const& stdString ) noexcept
623         :   m_start( stdString.c_str() ),
624             m_size( stdString.size() )
625         {}
626 
operator std::string() const627         explicit operator std::string() const {
628             return std::string(m_start, m_size);
629         }
630 
631     public: // operators
632         auto operator == ( StringRef const& other ) const noexcept -> bool;
operator !=(StringRef const & other) const633         auto operator != (StringRef const& other) const noexcept -> bool {
634             return !(*this == other);
635         }
636 
operator [](size_type index) const637         auto operator[] ( size_type index ) const noexcept -> char {
638             assert(index < m_size);
639             return m_start[index];
640         }
641 
642     public: // named queries
empty() const643         constexpr auto empty() const noexcept -> bool {
644             return m_size == 0;
645         }
size() const646         constexpr auto size() const noexcept -> size_type {
647             return m_size;
648         }
649 
650         // Returns the current start pointer. If the StringRef is not
651         // null-terminated, throws std::domain_exception
652         auto c_str() const -> char const*;
653 
654     public: // substrings and searches
655         // Returns a substring of [start, start + length).
656         // If start + length > size(), then the substring is [start, size()).
657         // If start > size(), then the substring is empty.
658         auto substr( size_type start, size_type length ) const noexcept -> StringRef;
659 
660         // Returns the current start pointer. May not be null-terminated.
661         auto data() const noexcept -> char const*;
662 
isNullTerminated() const663         constexpr auto isNullTerminated() const noexcept -> bool {
664             return m_start[m_size] == '\0';
665         }
666 
667     public: // iterators
begin() const668         constexpr const_iterator begin() const { return m_start; }
end() const669         constexpr const_iterator end() const { return m_start + m_size; }
670     };
671 
672     auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
673     auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
674 
operator ""_sr(char const * rawChars,std::size_t size)675     constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
676         return StringRef( rawChars, size );
677     }
678 } // namespace Catch
679 
operator ""_catch_sr(char const * rawChars,std::size_t size)680 constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
681     return Catch::StringRef( rawChars, size );
682 }
683 
684 // end catch_stringref.h
685 // start catch_preprocessor.hpp
686 
687 
688 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
689 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
690 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
691 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
692 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
693 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
694 
695 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
696 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
697 // MSVC needs more evaluations
698 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
699 #define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
700 #else
701 #define CATCH_RECURSE(...)  CATCH_RECURSION_LEVEL5(__VA_ARGS__)
702 #endif
703 
704 #define CATCH_REC_END(...)
705 #define CATCH_REC_OUT
706 
707 #define CATCH_EMPTY()
708 #define CATCH_DEFER(id) id CATCH_EMPTY()
709 
710 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
711 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
712 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
713 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
714 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
715 #define CATCH_REC_NEXT(test, next)  CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
716 
717 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
718 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
719 #define CATCH_REC_LIST2(f, x, peek, ...)   f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
720 
721 #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__ )
722 #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__ )
723 #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__ )
724 
725 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
726 // and passes userdata as the first parameter to each invocation,
727 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
728 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
729 
730 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
731 
732 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
733 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
734 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
735 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
736 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
737 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
738 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
739 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
740 #else
741 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
742 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
743 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
744 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
745 #endif
746 
747 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
748 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
749 
750 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
751 
752 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
753 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
754 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
755 #else
756 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
757 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
758 #endif
759 
760 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
761     CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
762 
763 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
764 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
765 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
766 #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)
767 #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)
768 #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)
769 #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, _3, _4, _5, _6)
770 #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)
771 #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)
772 #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)
773 #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)
774 
775 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
776 
777 #define INTERNAL_CATCH_TYPE_GEN\
778     template<typename...> struct TypeList {};\
779     template<typename...Ts>\
780     constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
781     template<template<typename...> class...> struct TemplateTypeList{};\
782     template<template<typename...> class...Cs>\
783     constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
784     template<typename...>\
785     struct append;\
786     template<typename...>\
787     struct rewrap;\
788     template<template<typename...> class, typename...>\
789     struct create;\
790     template<template<typename...> class, typename>\
791     struct convert;\
792     \
793     template<typename T> \
794     struct append<T> { using type = T; };\
795     template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
796     struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
797     template< template<typename...> class L1, typename...E1, typename...Rest>\
798     struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
799     \
800     template< template<typename...> class Container, template<typename...> class List, typename...elems>\
801     struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
802     template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
803     struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
804     \
805     template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
806     struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
807     template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
808     struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
809 
810 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
811     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
812     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
813     constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
814     template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
815     template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
816     constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
817     \
818     template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
819     struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
820     template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
821     struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
822     template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
823     struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
824 
825 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
826 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
827     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
828     static void TestName()
829 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
830     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
831     static void TestName()
832 
833 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
834 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
835     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
836     static void TestName()
837 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
838     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
839     static void TestName()
840 
841 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
842     template<typename Type>\
843     void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
844     {\
845         Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
846     }
847 
848 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
849     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
850     void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
851     {\
852         Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
853     }
854 
855 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
856     template<typename Type>\
857     void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
858     {\
859         Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
860     }
861 
862 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
863     template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
864     void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
865     {\
866         Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
867     }
868 
869 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
870 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
871     template<typename TestType> \
872     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
873         void test();\
874     }
875 
876 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
877     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
878     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
879         void test();\
880     }
881 
882 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
883 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
884     template<typename TestType> \
885     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
886 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
887     template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
888     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
889 
890 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
891 #define INTERNAL_CATCH_NTTP_0
892 #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)
893 #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__)
894 #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__)
895 #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__)
896 #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__)
897 #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__)
898 #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__)
899 #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__)
900 #else
901 #define INTERNAL_CATCH_NTTP_0(signature)
902 #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__))
903 #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__))
904 #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__))
905 #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__))
906 #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__))
907 #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__))
908 #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__))
909 #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__))
910 #endif
911 
912 // end catch_preprocessor.hpp
913 // start catch_meta.hpp
914 
915 
916 #include <type_traits>
917 
918 namespace Catch {
919     template<typename T>
920     struct always_false : std::false_type {};
921 
922     template <typename> struct true_given : std::true_type {};
923     struct is_callable_tester {
924         template <typename Fun, typename... Args>
925         true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
926         template <typename...>
927         std::false_type static test(...);
928     };
929 
930     template <typename T>
931     struct is_callable;
932 
933     template <typename Fun, typename... Args>
934     struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
935 
936 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
937     // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
938     // replaced with std::invoke_result here.
939     template <typename Func, typename... U>
940     using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
941 #else
942     // Keep ::type here because we still support C++11
943     template <typename Func, typename... U>
944     using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
945 #endif
946 
947 } // namespace Catch
948 
949 namespace mpl_{
950     struct na;
951 }
952 
953 // end catch_meta.hpp
954 namespace Catch {
955 
956 template<typename C>
957 class TestInvokerAsMethod : public ITestInvoker {
958     void (C::*m_testAsMethod)();
959 public:
TestInvokerAsMethod(void (C::* testAsMethod)())960     TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
961 
invoke() const962     void invoke() const override {
963         C obj;
964         (obj.*m_testAsMethod)();
965     }
966 };
967 
968 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
969 
970 template<typename C>
makeTestInvoker(void (C::* testAsMethod)())971 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
972     return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
973 }
974 
975 struct NameAndTags {
976     NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
977     StringRef name;
978     StringRef tags;
979 };
980 
981 struct AutoReg : NonCopyable {
982     AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
983     ~AutoReg();
984 };
985 
986 } // end namespace Catch
987 
988 #if defined(CATCH_CONFIG_DISABLE)
989     #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
990         static void TestName()
991     #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
992         namespace{                        \
993             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
994                 void test();              \
995             };                            \
996         }                                 \
997         void TestName::test()
998     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... )  \
999         INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1000     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... )    \
1001         namespace{                                                                                  \
1002             namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                      \
1003             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1004         }                                                                                           \
1005         }                                                                                           \
1006         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1007 
1008     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1009         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1010             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__ )
1011     #else
1012         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1013             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__ ) )
1014     #endif
1015 
1016     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1017         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1018             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__ )
1019     #else
1020         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1021             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__ ) )
1022     #endif
1023 
1024     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1025         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1026             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__ )
1027     #else
1028         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1029             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__ ) )
1030     #endif
1031 
1032     #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1033         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1034             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__ )
1035     #else
1036         #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1037             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__ ) )
1038     #endif
1039 #endif
1040 
1041     ///////////////////////////////////////////////////////////////////////////////
1042     #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1043         static void TestName(); \
1044         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1045         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1046         namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1047         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1048         static void TestName()
1049     #define INTERNAL_CATCH_TESTCASE( ... ) \
1050         INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1051 
1052     ///////////////////////////////////////////////////////////////////////////////
1053     #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1054         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1055         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1056         namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1057         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1058 
1059     ///////////////////////////////////////////////////////////////////////////////
1060     #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1061         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1062         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1063         namespace{ \
1064             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1065                 void test(); \
1066             }; \
1067             Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1068         } \
1069         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1070         void TestName::test()
1071     #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1072         INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1073 
1074     ///////////////////////////////////////////////////////////////////////////////
1075     #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1076         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1077         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1078         Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1079         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1080 
1081     ///////////////////////////////////////////////////////////////////////////////
1082     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1083         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1084         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1085         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1086         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1087         INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1088         namespace {\
1089         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1090             INTERNAL_CATCH_TYPE_GEN\
1091             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1092             INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1093             template<typename...Types> \
1094             struct TestName{\
1095                 TestName(){\
1096                     int index = 0;                                    \
1097                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1098                     using expander = int[];\
1099                     (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1100                 }\
1101             };\
1102             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1103             TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1104             return 0;\
1105         }();\
1106         }\
1107         }\
1108         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1109         INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1110 
1111 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1112     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1113         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__ )
1114 #else
1115     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1116         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__ ) )
1117 #endif
1118 
1119 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1120     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1121         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__ )
1122 #else
1123     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1124         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__ ) )
1125 #endif
1126 
1127     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1128         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                      \
1129         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                      \
1130         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                \
1131         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS              \
1132         template<typename TestType> static void TestFuncName();       \
1133         namespace {\
1134         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                     \
1135             INTERNAL_CATCH_TYPE_GEN                                                  \
1136             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))         \
1137             template<typename... Types>                               \
1138             struct TestName {                                         \
1139                 void reg_tests() {                                          \
1140                     int index = 0;                                    \
1141                     using expander = int[];                           \
1142                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1143                     constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1144                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1145                     (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++)... };/* NOLINT */\
1146                 }                                                     \
1147             };                                                        \
1148             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1149                 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1150                 TestInit t;                                           \
1151                 t.reg_tests();                                        \
1152                 return 0;                                             \
1153             }();                                                      \
1154         }                                                             \
1155         }                                                             \
1156         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                       \
1157         template<typename TestType>                                   \
1158         static void TestFuncName()
1159 
1160 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1161     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1162         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__)
1163 #else
1164     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1165         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__ ) )
1166 #endif
1167 
1168 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1169     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1170         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__)
1171 #else
1172     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1173         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__ ) )
1174 #endif
1175 
1176     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1177         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1178         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1179         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1180         template<typename TestType> static void TestFunc();       \
1181         namespace {\
1182         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1183         INTERNAL_CATCH_TYPE_GEN\
1184         template<typename... Types>                               \
1185         struct TestName {                                         \
1186             void reg_tests() {                                          \
1187                 int index = 0;                                    \
1188                 using expander = int[];                           \
1189                 (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++)... };/* NOLINT */\
1190             }                                                     \
1191         };\
1192         static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1193                 using TestInit = typename convert<TestName, TmplList>::type; \
1194                 TestInit t;                                           \
1195                 t.reg_tests();                                        \
1196                 return 0;                                             \
1197             }();                                                      \
1198         }}\
1199         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                       \
1200         template<typename TestType>                                   \
1201         static void TestFunc()
1202 
1203     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1204         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 )
1205 
1206     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1207         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1208         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1209         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1210         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1211         namespace {\
1212         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1213             INTERNAL_CATCH_TYPE_GEN\
1214             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1215             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1216             INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1217             template<typename...Types> \
1218             struct TestNameClass{\
1219                 TestNameClass(){\
1220                     int index = 0;                                    \
1221                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1222                     using expander = int[];\
1223                     (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1224                 }\
1225             };\
1226             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1227                 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1228                 return 0;\
1229         }();\
1230         }\
1231         }\
1232         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1233         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1234 
1235 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1236     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1237         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__ )
1238 #else
1239     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1240         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__ ) )
1241 #endif
1242 
1243 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1244     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1245         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__ )
1246 #else
1247     #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1248         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__ ) )
1249 #endif
1250 
1251     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1252         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1253         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1254         CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1255         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1256         template<typename TestType> \
1257             struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1258                 void test();\
1259             };\
1260         namespace {\
1261         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1262             INTERNAL_CATCH_TYPE_GEN                  \
1263             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1264             template<typename...Types>\
1265             struct TestNameClass{\
1266                 void reg_tests(){\
1267                     int index = 0;\
1268                     using expander = int[];\
1269                     constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1270                     constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1271                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1272                     (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++)... };/* NOLINT */ \
1273                 }\
1274             };\
1275             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1276                 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1277                 TestInit t;\
1278                 t.reg_tests();\
1279                 return 0;\
1280             }(); \
1281         }\
1282         }\
1283         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1284         template<typename TestType> \
1285         void TestName<TestType>::test()
1286 
1287 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1288     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1289         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__ )
1290 #else
1291     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1292         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__ ) )
1293 #endif
1294 
1295 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1296     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1297         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__ )
1298 #else
1299     #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1300         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__ ) )
1301 #endif
1302 
1303     #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1304         CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1305         CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1306         CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1307         template<typename TestType> \
1308         struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1309             void test();\
1310         };\
1311         namespace {\
1312         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1313             INTERNAL_CATCH_TYPE_GEN\
1314             template<typename...Types>\
1315             struct TestNameClass{\
1316                 void reg_tests(){\
1317                     int index = 0;\
1318                     using expander = int[];\
1319                     (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++)... };/* NOLINT */ \
1320                 }\
1321             };\
1322             static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1323                 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1324                 TestInit t;\
1325                 t.reg_tests();\
1326                 return 0;\
1327             }(); \
1328         }}\
1329         CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1330         template<typename TestType> \
1331         void TestName<TestType>::test()
1332 
1333 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1334         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 )
1335 
1336 // end catch_test_registry.h
1337 // start catch_capture.hpp
1338 
1339 // start catch_assertionhandler.h
1340 
1341 // start catch_assertioninfo.h
1342 
1343 // start catch_result_type.h
1344 
1345 namespace Catch {
1346 
1347     // ResultWas::OfType enum
1348     struct ResultWas { enum OfType {
1349         Unknown = -1,
1350         Ok = 0,
1351         Info = 1,
1352         Warning = 2,
1353 
1354         FailureBit = 0x10,
1355 
1356         ExpressionFailed = FailureBit | 1,
1357         ExplicitFailure = FailureBit | 2,
1358 
1359         Exception = 0x100 | FailureBit,
1360 
1361         ThrewException = Exception | 1,
1362         DidntThrowException = Exception | 2,
1363 
1364         FatalErrorCondition = 0x200 | FailureBit
1365 
1366     }; };
1367 
1368     bool isOk( ResultWas::OfType resultType );
1369     bool isJustInfo( int flags );
1370 
1371     // ResultDisposition::Flags enum
1372     struct ResultDisposition { enum Flags {
1373         Normal = 0x01,
1374 
1375         ContinueOnFailure = 0x02,   // Failures fail test, but execution continues
1376         FalseTest = 0x04,           // Prefix expression with !
1377         SuppressFail = 0x08         // Failures are reported but do not fail the test
1378     }; };
1379 
1380     ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1381 
1382     bool shouldContinueOnFailure( int flags );
isFalseTest(int flags)1383     inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1384     bool shouldSuppressFailure( int flags );
1385 
1386 } // end namespace Catch
1387 
1388 // end catch_result_type.h
1389 namespace Catch {
1390 
1391     struct AssertionInfo
1392     {
1393         StringRef macroName;
1394         SourceLineInfo lineInfo;
1395         StringRef capturedExpression;
1396         ResultDisposition::Flags resultDisposition;
1397 
1398         // We want to delete this constructor but a compiler bug in 4.8 means
1399         // the struct is then treated as non-aggregate
1400         //AssertionInfo() = delete;
1401     };
1402 
1403 } // end namespace Catch
1404 
1405 // end catch_assertioninfo.h
1406 // start catch_decomposer.h
1407 
1408 // start catch_tostring.h
1409 
1410 #include <vector>
1411 #include <cstddef>
1412 #include <type_traits>
1413 #include <string>
1414 // start catch_stream.h
1415 
1416 #include <iosfwd>
1417 #include <cstddef>
1418 #include <ostream>
1419 
1420 namespace Catch {
1421 
1422     std::ostream& cout();
1423     std::ostream& cerr();
1424     std::ostream& clog();
1425 
1426     class StringRef;
1427 
1428     struct IStream {
1429         virtual ~IStream();
1430         virtual std::ostream& stream() const = 0;
1431     };
1432 
1433     auto makeStream( StringRef const &filename ) -> IStream const*;
1434 
1435     class ReusableStringStream : NonCopyable {
1436         std::size_t m_index;
1437         std::ostream* m_oss;
1438     public:
1439         ReusableStringStream();
1440         ~ReusableStringStream();
1441 
1442         auto str() const -> std::string;
1443 
1444         template<typename T>
operator <<(T const & value)1445         auto operator << ( T const& value ) -> ReusableStringStream& {
1446             *m_oss << value;
1447             return *this;
1448         }
get()1449         auto get() -> std::ostream& { return *m_oss; }
1450     };
1451 }
1452 
1453 // end catch_stream.h
1454 // start catch_interfaces_enum_values_registry.h
1455 
1456 #include <vector>
1457 
1458 namespace Catch {
1459 
1460     namespace Detail {
1461         struct EnumInfo {
1462             StringRef m_name;
1463             std::vector<std::pair<int, StringRef>> m_values;
1464 
1465             ~EnumInfo();
1466 
1467             StringRef lookup( int value ) const;
1468         };
1469     } // namespace Detail
1470 
1471     struct IMutableEnumValuesRegistry {
1472         virtual ~IMutableEnumValuesRegistry();
1473 
1474         virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1475 
1476         template<typename E>
registerEnumCatch::IMutableEnumValuesRegistry1477         Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1478             static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1479             std::vector<int> intValues;
1480             intValues.reserve( values.size() );
1481             for( auto enumValue : values )
1482                 intValues.push_back( static_cast<int>( enumValue ) );
1483             return registerEnum( enumName, allEnums, intValues );
1484         }
1485     };
1486 
1487 } // Catch
1488 
1489 // end catch_interfaces_enum_values_registry.h
1490 
1491 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1492 #include <string_view>
1493 #endif
1494 
1495 #ifdef __OBJC__
1496 // start catch_objc_arc.hpp
1497 
1498 #import <Foundation/Foundation.h>
1499 
1500 #ifdef __has_feature
1501 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1502 #else
1503 #define CATCH_ARC_ENABLED 0
1504 #endif
1505 
1506 void arcSafeRelease( NSObject* obj );
1507 id performOptionalSelector( id obj, SEL sel );
1508 
1509 #if !CATCH_ARC_ENABLED
arcSafeRelease(NSObject * obj)1510 inline void arcSafeRelease( NSObject* obj ) {
1511     [obj release];
1512 }
performOptionalSelector(id obj,SEL sel)1513 inline id performOptionalSelector( id obj, SEL sel ) {
1514     if( [obj respondsToSelector: sel] )
1515         return [obj performSelector: sel];
1516     return nil;
1517 }
1518 #define CATCH_UNSAFE_UNRETAINED
1519 #define CATCH_ARC_STRONG
1520 #else
arcSafeRelease(NSObject *)1521 inline void arcSafeRelease( NSObject* ){}
performOptionalSelector(id obj,SEL sel)1522 inline id performOptionalSelector( id obj, SEL sel ) {
1523 #ifdef __clang__
1524 #pragma clang diagnostic push
1525 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1526 #endif
1527     if( [obj respondsToSelector: sel] )
1528         return [obj performSelector: sel];
1529 #ifdef __clang__
1530 #pragma clang diagnostic pop
1531 #endif
1532     return nil;
1533 }
1534 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1535 #define CATCH_ARC_STRONG __strong
1536 #endif
1537 
1538 // end catch_objc_arc.hpp
1539 #endif
1540 
1541 #ifdef _MSC_VER
1542 #pragma warning(push)
1543 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1544 #endif
1545 
1546 namespace Catch {
1547     namespace Detail {
1548 
1549         extern const std::string unprintableString;
1550 
1551         std::string rawMemoryToString( const void *object, std::size_t size );
1552 
1553         template<typename T>
rawMemoryToString(const T & object)1554         std::string rawMemoryToString( const T& object ) {
1555           return rawMemoryToString( &object, sizeof(object) );
1556         }
1557 
1558         template<typename T>
1559         class IsStreamInsertable {
1560             template<typename Stream, typename U>
1561             static auto test(int)
1562                 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1563 
1564             template<typename, typename>
1565             static auto test(...)->std::false_type;
1566 
1567         public:
1568             static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1569         };
1570 
1571         template<typename E>
1572         std::string convertUnknownEnumToString( E e );
1573 
1574         template<typename T>
1575         typename std::enable_if<
1576             !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const &)1577         std::string>::type convertUnstreamable( T const& ) {
1578             return Detail::unprintableString;
1579         }
1580         template<typename T>
1581         typename std::enable_if<
1582             !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
convertUnstreamable(T const & ex)1583          std::string>::type convertUnstreamable(T const& ex) {
1584             return ex.what();
1585         }
1586 
1587         template<typename T>
1588         typename std::enable_if<
1589             std::is_enum<T>::value
convertUnstreamable(T const & value)1590         , std::string>::type convertUnstreamable( T const& value ) {
1591             return convertUnknownEnumToString( value );
1592         }
1593 
1594 #if defined(_MANAGED)
1595         //! Convert a CLR string to a utf8 std::string
1596         template<typename T>
1597         std::string clrReferenceToString( T^ ref ) {
1598             if (ref == nullptr)
1599                 return std::string("null");
1600             auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1601             cli::pin_ptr<System::Byte> p = &bytes[0];
1602             return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1603         }
1604 #endif
1605 
1606     } // namespace Detail
1607 
1608     // If we decide for C++14, change these to enable_if_ts
1609     template <typename T, typename = void>
1610     struct StringMaker {
1611         template <typename Fake = T>
1612         static
1613         typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1614             convert(const Fake& value) {
1615                 ReusableStringStream rss;
1616                 // NB: call using the function-like syntax to avoid ambiguity with
1617                 // user-defined templated operator<< under clang.
1618                 rss.operator<<(value);
1619                 return rss.str();
1620         }
1621 
1622         template <typename Fake = T>
1623         static
1624         typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
convertCatch::StringMaker1625             convert( const Fake& value ) {
1626 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1627             return Detail::convertUnstreamable(value);
1628 #else
1629             return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1630 #endif
1631         }
1632     };
1633 
1634     namespace Detail {
1635 
1636         // This function dispatches all stringification requests inside of Catch.
1637         // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1638         template <typename T>
stringify(const T & e)1639         std::string stringify(const T& e) {
1640             return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1641         }
1642 
1643         template<typename E>
convertUnknownEnumToString(E e)1644         std::string convertUnknownEnumToString( E e ) {
1645             return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1646         }
1647 
1648 #if defined(_MANAGED)
1649         template <typename T>
1650         std::string stringify( T^ e ) {
1651             return ::Catch::StringMaker<T^>::convert(e);
1652         }
1653 #endif
1654 
1655     } // namespace Detail
1656 
1657     // Some predefined specializations
1658 
1659     template<>
1660     struct StringMaker<std::string> {
1661         static std::string convert(const std::string& str);
1662     };
1663 
1664 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1665     template<>
1666     struct StringMaker<std::string_view> {
1667         static std::string convert(std::string_view str);
1668     };
1669 #endif
1670 
1671     template<>
1672     struct StringMaker<char const *> {
1673         static std::string convert(char const * str);
1674     };
1675     template<>
1676     struct StringMaker<char *> {
1677         static std::string convert(char * str);
1678     };
1679 
1680 #ifdef CATCH_CONFIG_WCHAR
1681     template<>
1682     struct StringMaker<std::wstring> {
1683         static std::string convert(const std::wstring& wstr);
1684     };
1685 
1686 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1687     template<>
1688     struct StringMaker<std::wstring_view> {
1689         static std::string convert(std::wstring_view str);
1690     };
1691 # endif
1692 
1693     template<>
1694     struct StringMaker<wchar_t const *> {
1695         static std::string convert(wchar_t const * str);
1696     };
1697     template<>
1698     struct StringMaker<wchar_t *> {
1699         static std::string convert(wchar_t * str);
1700     };
1701 #endif
1702 
1703     // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1704     //      while keeping string semantics?
1705     template<int SZ>
1706     struct StringMaker<char[SZ]> {
convertCatch::StringMaker1707         static std::string convert(char const* str) {
1708             return ::Catch::Detail::stringify(std::string{ str });
1709         }
1710     };
1711     template<int SZ>
1712     struct StringMaker<signed char[SZ]> {
convertCatch::StringMaker1713         static std::string convert(signed char const* str) {
1714             return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1715         }
1716     };
1717     template<int SZ>
1718     struct StringMaker<unsigned char[SZ]> {
convertCatch::StringMaker1719         static std::string convert(unsigned char const* str) {
1720             return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1721         }
1722     };
1723 
1724 #if defined(CATCH_CONFIG_CPP17_BYTE)
1725     template<>
1726     struct StringMaker<std::byte> {
1727         static std::string convert(std::byte value);
1728     };
1729 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1730     template<>
1731     struct StringMaker<int> {
1732         static std::string convert(int value);
1733     };
1734     template<>
1735     struct StringMaker<long> {
1736         static std::string convert(long value);
1737     };
1738     template<>
1739     struct StringMaker<long long> {
1740         static std::string convert(long long value);
1741     };
1742     template<>
1743     struct StringMaker<unsigned int> {
1744         static std::string convert(unsigned int value);
1745     };
1746     template<>
1747     struct StringMaker<unsigned long> {
1748         static std::string convert(unsigned long value);
1749     };
1750     template<>
1751     struct StringMaker<unsigned long long> {
1752         static std::string convert(unsigned long long value);
1753     };
1754 
1755     template<>
1756     struct StringMaker<bool> {
1757         static std::string convert(bool b);
1758     };
1759 
1760     template<>
1761     struct StringMaker<char> {
1762         static std::string convert(char c);
1763     };
1764     template<>
1765     struct StringMaker<signed char> {
1766         static std::string convert(signed char c);
1767     };
1768     template<>
1769     struct StringMaker<unsigned char> {
1770         static std::string convert(unsigned char c);
1771     };
1772 
1773     template<>
1774     struct StringMaker<std::nullptr_t> {
1775         static std::string convert(std::nullptr_t);
1776     };
1777 
1778     template<>
1779     struct StringMaker<float> {
1780         static std::string convert(float value);
1781         static int precision;
1782     };
1783 
1784     template<>
1785     struct StringMaker<double> {
1786         static std::string convert(double value);
1787         static int precision;
1788     };
1789 
1790     template <typename T>
1791     struct StringMaker<T*> {
1792         template <typename U>
convertCatch::StringMaker1793         static std::string convert(U* p) {
1794             if (p) {
1795                 return ::Catch::Detail::rawMemoryToString(p);
1796             } else {
1797                 return "nullptr";
1798             }
1799         }
1800     };
1801 
1802     template <typename R, typename C>
1803     struct StringMaker<R C::*> {
convertCatch::StringMaker1804         static std::string convert(R C::* p) {
1805             if (p) {
1806                 return ::Catch::Detail::rawMemoryToString(p);
1807             } else {
1808                 return "nullptr";
1809             }
1810         }
1811     };
1812 
1813 #if defined(_MANAGED)
1814     template <typename T>
1815     struct StringMaker<T^> {
1816         static std::string convert( T^ ref ) {
1817             return ::Catch::Detail::clrReferenceToString(ref);
1818         }
1819     };
1820 #endif
1821 
1822     namespace Detail {
1823         template<typename InputIterator, typename Sentinel = InputIterator>
rangeToString(InputIterator first,Sentinel last)1824         std::string rangeToString(InputIterator first, Sentinel last) {
1825             ReusableStringStream rss;
1826             rss << "{ ";
1827             if (first != last) {
1828                 rss << ::Catch::Detail::stringify(*first);
1829                 for (++first; first != last; ++first)
1830                     rss << ", " << ::Catch::Detail::stringify(*first);
1831             }
1832             rss << " }";
1833             return rss.str();
1834         }
1835     }
1836 
1837 #ifdef __OBJC__
1838     template<>
1839     struct StringMaker<NSString*> {
convertCatch::StringMaker1840         static std::string convert(NSString * nsstring) {
1841             if (!nsstring)
1842                 return "nil";
1843             return std::string("@") + [nsstring UTF8String];
1844         }
1845     };
1846     template<>
1847     struct StringMaker<NSObject*> {
convertCatch::StringMaker1848         static std::string convert(NSObject* nsObject) {
1849             return ::Catch::Detail::stringify([nsObject description]);
1850         }
1851 
1852     };
1853     namespace Detail {
stringify(NSString * nsstring)1854         inline std::string stringify( NSString* nsstring ) {
1855             return StringMaker<NSString*>::convert( nsstring );
1856         }
1857 
1858     } // namespace Detail
1859 #endif // __OBJC__
1860 
1861 } // namespace Catch
1862 
1863 //////////////////////////////////////////////////////
1864 // Separate std-lib types stringification, so it can be selectively enabled
1865 // This means that we do not bring in
1866 
1867 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1868 #  define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1869 #  define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1870 #  define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1871 #  define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1872 #  define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1873 #endif
1874 
1875 // Separate std::pair specialization
1876 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1877 #include <utility>
1878 namespace Catch {
1879     template<typename T1, typename T2>
1880     struct StringMaker<std::pair<T1, T2> > {
convertCatch::StringMaker1881         static std::string convert(const std::pair<T1, T2>& pair) {
1882             ReusableStringStream rss;
1883             rss << "{ "
1884                 << ::Catch::Detail::stringify(pair.first)
1885                 << ", "
1886                 << ::Catch::Detail::stringify(pair.second)
1887                 << " }";
1888             return rss.str();
1889         }
1890     };
1891 }
1892 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1893 
1894 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1895 #include <optional>
1896 namespace Catch {
1897     template<typename T>
1898     struct StringMaker<std::optional<T> > {
convertCatch::StringMaker1899         static std::string convert(const std::optional<T>& optional) {
1900             ReusableStringStream rss;
1901             if (optional.has_value()) {
1902                 rss << ::Catch::Detail::stringify(*optional);
1903             } else {
1904                 rss << "{ }";
1905             }
1906             return rss.str();
1907         }
1908     };
1909 }
1910 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1911 
1912 // Separate std::tuple specialization
1913 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1914 #include <tuple>
1915 namespace Catch {
1916     namespace Detail {
1917         template<
1918             typename Tuple,
1919             std::size_t N = 0,
1920             bool = (N < std::tuple_size<Tuple>::value)
1921             >
1922             struct TupleElementPrinter {
printCatch::Detail::TupleElementPrinter1923             static void print(const Tuple& tuple, std::ostream& os) {
1924                 os << (N ? ", " : " ")
1925                     << ::Catch::Detail::stringify(std::get<N>(tuple));
1926                 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1927             }
1928         };
1929 
1930         template<
1931             typename Tuple,
1932             std::size_t N
1933         >
1934             struct TupleElementPrinter<Tuple, N, false> {
printCatch::Detail::TupleElementPrinter1935             static void print(const Tuple&, std::ostream&) {}
1936         };
1937 
1938     }
1939 
1940     template<typename ...Types>
1941     struct StringMaker<std::tuple<Types...>> {
convertCatch::StringMaker1942         static std::string convert(const std::tuple<Types...>& tuple) {
1943             ReusableStringStream rss;
1944             rss << '{';
1945             Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1946             rss << " }";
1947             return rss.str();
1948         }
1949     };
1950 }
1951 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1952 
1953 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1954 #include <variant>
1955 namespace Catch {
1956     template<>
1957     struct StringMaker<std::monostate> {
convertCatch::StringMaker1958         static std::string convert(const std::monostate&) {
1959             return "{ }";
1960         }
1961     };
1962 
1963     template<typename... Elements>
1964     struct StringMaker<std::variant<Elements...>> {
convertCatch::StringMaker1965         static std::string convert(const std::variant<Elements...>& variant) {
1966             if (variant.valueless_by_exception()) {
1967                 return "{valueless variant}";
1968             } else {
1969                 return std::visit(
1970                     [](const auto& value) {
1971                         return ::Catch::Detail::stringify(value);
1972                     },
1973                     variant
1974                 );
1975             }
1976         }
1977     };
1978 }
1979 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1980 
1981 namespace Catch {
1982     // Import begin/ end from std here
1983     using std::begin;
1984     using std::end;
1985 
1986     namespace detail {
1987         template <typename...>
1988         struct void_type {
1989             using type = void;
1990         };
1991 
1992         template <typename T, typename = void>
1993         struct is_range_impl : std::false_type {
1994         };
1995 
1996         template <typename T>
1997         struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type> : std::true_type {
1998         };
1999     } // namespace detail
2000 
2001     template <typename T>
2002     struct is_range : detail::is_range_impl<T> {
2003     };
2004 
2005 #if defined(_MANAGED) // Managed types are never ranges
2006     template <typename T>
2007     struct is_range<T^> {
2008         static const bool value = false;
2009     };
2010 #endif
2011 
2012     template<typename Range>
rangeToString(Range const & range)2013     std::string rangeToString( Range const& range ) {
2014         return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2015     }
2016 
2017     // Handle vector<bool> specially
2018     template<typename Allocator>
rangeToString(std::vector<bool,Allocator> const & v)2019     std::string rangeToString( std::vector<bool, Allocator> const& v ) {
2020         ReusableStringStream rss;
2021         rss << "{ ";
2022         bool first = true;
2023         for( bool b : v ) {
2024             if( first )
2025                 first = false;
2026             else
2027                 rss << ", ";
2028             rss << ::Catch::Detail::stringify( b );
2029         }
2030         rss << " }";
2031         return rss.str();
2032     }
2033 
2034     template<typename R>
2035     struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
convertCatch::StringMaker2036         static std::string convert( R const& range ) {
2037             return rangeToString( range );
2038         }
2039     };
2040 
2041     template <typename T, int SZ>
2042     struct StringMaker<T[SZ]> {
convertCatch::StringMaker2043         static std::string convert(T const(&arr)[SZ]) {
2044             return rangeToString(arr);
2045         }
2046     };
2047 
2048 } // namespace Catch
2049 
2050 // Separate std::chrono::duration specialization
2051 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2052 #include <ctime>
2053 #include <ratio>
2054 #include <chrono>
2055 
2056 namespace Catch {
2057 
2058 template <class Ratio>
2059 struct ratio_string {
2060     static std::string symbol();
2061 };
2062 
2063 template <class Ratio>
symbol()2064 std::string ratio_string<Ratio>::symbol() {
2065     Catch::ReusableStringStream rss;
2066     rss << '[' << Ratio::num << '/'
2067         << Ratio::den << ']';
2068     return rss.str();
2069 }
2070 template <>
2071 struct ratio_string<std::atto> {
2072     static std::string symbol();
2073 };
2074 template <>
2075 struct ratio_string<std::femto> {
2076     static std::string symbol();
2077 };
2078 template <>
2079 struct ratio_string<std::pico> {
2080     static std::string symbol();
2081 };
2082 template <>
2083 struct ratio_string<std::nano> {
2084     static std::string symbol();
2085 };
2086 template <>
2087 struct ratio_string<std::micro> {
2088     static std::string symbol();
2089 };
2090 template <>
2091 struct ratio_string<std::milli> {
2092     static std::string symbol();
2093 };
2094 
2095     ////////////
2096     // std::chrono::duration specializations
2097     template<typename Value, typename Ratio>
2098     struct StringMaker<std::chrono::duration<Value, Ratio>> {
convertCatch::StringMaker2099         static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2100             ReusableStringStream rss;
2101             rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2102             return rss.str();
2103         }
2104     };
2105     template<typename Value>
2106     struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
convertCatch::StringMaker2107         static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2108             ReusableStringStream rss;
2109             rss << duration.count() << " s";
2110             return rss.str();
2111         }
2112     };
2113     template<typename Value>
2114     struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
convertCatch::StringMaker2115         static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2116             ReusableStringStream rss;
2117             rss << duration.count() << " m";
2118             return rss.str();
2119         }
2120     };
2121     template<typename Value>
2122     struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
convertCatch::StringMaker2123         static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2124             ReusableStringStream rss;
2125             rss << duration.count() << " h";
2126             return rss.str();
2127         }
2128     };
2129 
2130     ////////////
2131     // std::chrono::time_point specialization
2132     // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2133     template<typename Clock, typename Duration>
2134     struct StringMaker<std::chrono::time_point<Clock, Duration>> {
convertCatch::StringMaker2135         static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2136             return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2137         }
2138     };
2139     // std::chrono::time_point<system_clock> specialization
2140     template<typename Duration>
2141     struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
convertCatch::StringMaker2142         static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2143             auto converted = std::chrono::system_clock::to_time_t(time_point);
2144 
2145 #ifdef _MSC_VER
2146             std::tm timeInfo = {};
2147             gmtime_s(&timeInfo, &converted);
2148 #else
2149             std::tm* timeInfo = std::gmtime(&converted);
2150 #endif
2151 
2152             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2153             char timeStamp[timeStampSize];
2154             const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2155 
2156 #ifdef _MSC_VER
2157             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2158 #else
2159             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2160 #endif
2161             return std::string(timeStamp);
2162         }
2163     };
2164 }
2165 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2166 
2167 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2168 namespace Catch { \
2169     template<> struct StringMaker<enumName> { \
2170         static std::string convert( enumName value ) { \
2171             static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2172             return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2173         } \
2174     }; \
2175 }
2176 
2177 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2178 
2179 #ifdef _MSC_VER
2180 #pragma warning(pop)
2181 #endif
2182 
2183 // end catch_tostring.h
2184 #include <iosfwd>
2185 
2186 #ifdef _MSC_VER
2187 #pragma warning(push)
2188 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2189 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2190 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2191 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2192 #pragma warning(disable:4800) // Forcing result to true or false
2193 #endif
2194 
2195 namespace Catch {
2196 
2197     struct ITransientExpression {
isBinaryExpressionCatch::ITransientExpression2198         auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
getResultCatch::ITransientExpression2199         auto getResult() const -> bool { return m_result; }
2200         virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2201 
ITransientExpressionCatch::ITransientExpression2202         ITransientExpression( bool isBinaryExpression, bool result )
2203         :   m_isBinaryExpression( isBinaryExpression ),
2204             m_result( result )
2205         {}
2206 
2207         // We don't actually need a virtual destructor, but many static analysers
2208         // complain if it's not here :-(
2209         virtual ~ITransientExpression();
2210 
2211         bool m_isBinaryExpression;
2212         bool m_result;
2213 
2214     };
2215 
2216     void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2217 
2218     template<typename LhsT, typename RhsT>
2219     class BinaryExpr  : public ITransientExpression {
2220         LhsT m_lhs;
2221         StringRef m_op;
2222         RhsT m_rhs;
2223 
streamReconstructedExpression(std::ostream & os) const2224         void streamReconstructedExpression( std::ostream &os ) const override {
2225             formatReconstructedExpression
2226                     ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2227         }
2228 
2229     public:
BinaryExpr(bool comparisonResult,LhsT lhs,StringRef op,RhsT rhs)2230         BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2231         :   ITransientExpression{ true, comparisonResult },
2232             m_lhs( lhs ),
2233             m_op( op ),
2234             m_rhs( rhs )
2235         {}
2236 
2237         template<typename T>
operator &&(T) const2238         auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2239             static_assert(always_false<T>::value,
2240             "chained comparisons are not supported inside assertions, "
2241             "wrap the expression inside parentheses, or decompose it");
2242         }
2243 
2244         template<typename T>
operator ||(T) const2245         auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2246             static_assert(always_false<T>::value,
2247             "chained comparisons are not supported inside assertions, "
2248             "wrap the expression inside parentheses, or decompose it");
2249         }
2250 
2251         template<typename T>
operator ==(T) const2252         auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2253             static_assert(always_false<T>::value,
2254             "chained comparisons are not supported inside assertions, "
2255             "wrap the expression inside parentheses, or decompose it");
2256         }
2257 
2258         template<typename T>
operator !=(T) const2259         auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2260             static_assert(always_false<T>::value,
2261             "chained comparisons are not supported inside assertions, "
2262             "wrap the expression inside parentheses, or decompose it");
2263         }
2264 
2265         template<typename T>
operator >(T) const2266         auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2267             static_assert(always_false<T>::value,
2268             "chained comparisons are not supported inside assertions, "
2269             "wrap the expression inside parentheses, or decompose it");
2270         }
2271 
2272         template<typename T>
operator <(T) const2273         auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2274             static_assert(always_false<T>::value,
2275             "chained comparisons are not supported inside assertions, "
2276             "wrap the expression inside parentheses, or decompose it");
2277         }
2278 
2279         template<typename T>
operator >=(T) const2280         auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2281             static_assert(always_false<T>::value,
2282             "chained comparisons are not supported inside assertions, "
2283             "wrap the expression inside parentheses, or decompose it");
2284         }
2285 
2286         template<typename T>
operator <=(T) const2287         auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2288             static_assert(always_false<T>::value,
2289             "chained comparisons are not supported inside assertions, "
2290             "wrap the expression inside parentheses, or decompose it");
2291         }
2292     };
2293 
2294     template<typename LhsT>
2295     class UnaryExpr : public ITransientExpression {
2296         LhsT m_lhs;
2297 
streamReconstructedExpression(std::ostream & os) const2298         void streamReconstructedExpression( std::ostream &os ) const override {
2299             os << Catch::Detail::stringify( m_lhs );
2300         }
2301 
2302     public:
UnaryExpr(LhsT lhs)2303         explicit UnaryExpr( LhsT lhs )
2304         :   ITransientExpression{ false, static_cast<bool>(lhs) },
2305             m_lhs( lhs )
2306         {}
2307     };
2308 
2309     // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2310     template<typename LhsT, typename RhsT>
compareEqual(LhsT const & lhs,RhsT const & rhs)2311     auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2312     template<typename T>
compareEqual(T * const & lhs,int rhs)2313     auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2314     template<typename T>
compareEqual(T * const & lhs,long rhs)2315     auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2316     template<typename T>
compareEqual(int lhs,T * const & rhs)2317     auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2318     template<typename T>
compareEqual(long lhs,T * const & rhs)2319     auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2320 
2321     template<typename LhsT, typename RhsT>
compareNotEqual(LhsT const & lhs,RhsT && rhs)2322     auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2323     template<typename T>
compareNotEqual(T * const & lhs,int rhs)2324     auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2325     template<typename T>
compareNotEqual(T * const & lhs,long rhs)2326     auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2327     template<typename T>
compareNotEqual(int lhs,T * const & rhs)2328     auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2329     template<typename T>
compareNotEqual(long lhs,T * const & rhs)2330     auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2331 
2332     template<typename LhsT>
2333     class ExprLhs {
2334         LhsT m_lhs;
2335     public:
ExprLhs(LhsT lhs)2336         explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2337 
2338         template<typename RhsT>
operator ==(RhsT const & rhs)2339         auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2340             return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2341         }
operator ==(bool rhs)2342         auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2343             return { m_lhs == rhs, m_lhs, "==", rhs };
2344         }
2345 
2346         template<typename RhsT>
operator !=(RhsT const & rhs)2347         auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2348             return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2349         }
operator !=(bool rhs)2350         auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2351             return { m_lhs != rhs, m_lhs, "!=", rhs };
2352         }
2353 
2354         template<typename RhsT>
operator >(RhsT const & rhs)2355         auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2356             return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2357         }
2358         template<typename RhsT>
operator <(RhsT const & rhs)2359         auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2360             return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2361         }
2362         template<typename RhsT>
operator >=(RhsT const & rhs)2363         auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2364             return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2365         }
2366         template<typename RhsT>
operator <=(RhsT const & rhs)2367         auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2368             return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2369         }
2370         template <typename RhsT>
operator |(RhsT const & rhs)2371         auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2372             return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
2373         }
2374         template <typename RhsT>
operator &(RhsT const & rhs)2375         auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2376             return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
2377         }
2378         template <typename RhsT>
operator ^(RhsT const & rhs)2379         auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2380             return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
2381         }
2382 
2383         template<typename RhsT>
operator &&(RhsT const &)2384         auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2385             static_assert(always_false<RhsT>::value,
2386             "operator&& is not supported inside assertions, "
2387             "wrap the expression inside parentheses, or decompose it");
2388         }
2389 
2390         template<typename RhsT>
operator ||(RhsT const &)2391         auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2392             static_assert(always_false<RhsT>::value,
2393             "operator|| is not supported inside assertions, "
2394             "wrap the expression inside parentheses, or decompose it");
2395         }
2396 
makeUnaryExpr() const2397         auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2398             return UnaryExpr<LhsT>{ m_lhs };
2399         }
2400     };
2401 
2402     void handleExpression( ITransientExpression const& expr );
2403 
2404     template<typename T>
handleExpression(ExprLhs<T> const & expr)2405     void handleExpression( ExprLhs<T> const& expr ) {
2406         handleExpression( expr.makeUnaryExpr() );
2407     }
2408 
2409     struct Decomposer {
2410         template<typename T>
operator <=Catch::Decomposer2411         auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2412             return ExprLhs<T const&>{ lhs };
2413         }
2414 
operator <=Catch::Decomposer2415         auto operator <=( bool value ) -> ExprLhs<bool> {
2416             return ExprLhs<bool>{ value };
2417         }
2418     };
2419 
2420 } // end namespace Catch
2421 
2422 #ifdef _MSC_VER
2423 #pragma warning(pop)
2424 #endif
2425 
2426 // end catch_decomposer.h
2427 // start catch_interfaces_capture.h
2428 
2429 #include <string>
2430 #include <chrono>
2431 
2432 namespace Catch {
2433 
2434     class AssertionResult;
2435     struct AssertionInfo;
2436     struct SectionInfo;
2437     struct SectionEndInfo;
2438     struct MessageInfo;
2439     struct MessageBuilder;
2440     struct Counts;
2441     struct AssertionReaction;
2442     struct SourceLineInfo;
2443 
2444     struct ITransientExpression;
2445     struct IGeneratorTracker;
2446 
2447 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2448     struct BenchmarkInfo;
2449     template <typename Duration = std::chrono::duration<double, std::nano>>
2450     struct BenchmarkStats;
2451 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2452 
2453     struct IResultCapture {
2454 
2455         virtual ~IResultCapture();
2456 
2457         virtual bool sectionStarted(    SectionInfo const& sectionInfo,
2458                                         Counts& assertions ) = 0;
2459         virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2460         virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2461 
2462         virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2463 
2464 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2465         virtual void benchmarkPreparing( std::string const& name ) = 0;
2466         virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2467         virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2468         virtual void benchmarkFailed( std::string const& error ) = 0;
2469 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2470 
2471         virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2472         virtual void popScopedMessage( MessageInfo const& message ) = 0;
2473 
2474         virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2475 
2476         virtual void handleFatalErrorCondition( StringRef message ) = 0;
2477 
2478         virtual void handleExpr
2479                 (   AssertionInfo const& info,
2480                     ITransientExpression const& expr,
2481                     AssertionReaction& reaction ) = 0;
2482         virtual void handleMessage
2483                 (   AssertionInfo const& info,
2484                     ResultWas::OfType resultType,
2485                     StringRef const& message,
2486                     AssertionReaction& reaction ) = 0;
2487         virtual void handleUnexpectedExceptionNotThrown
2488                 (   AssertionInfo const& info,
2489                     AssertionReaction& reaction ) = 0;
2490         virtual void handleUnexpectedInflightException
2491                 (   AssertionInfo const& info,
2492                     std::string const& message,
2493                     AssertionReaction& reaction ) = 0;
2494         virtual void handleIncomplete
2495                 (   AssertionInfo const& info ) = 0;
2496         virtual void handleNonExpr
2497                 (   AssertionInfo const &info,
2498                     ResultWas::OfType resultType,
2499                     AssertionReaction &reaction ) = 0;
2500 
2501         virtual bool lastAssertionPassed() = 0;
2502         virtual void assertionPassed() = 0;
2503 
2504         // Deprecated, do not use:
2505         virtual std::string getCurrentTestName() const = 0;
2506         virtual const AssertionResult* getLastResult() const = 0;
2507         virtual void exceptionEarlyReported() = 0;
2508     };
2509 
2510     IResultCapture& getResultCapture();
2511 }
2512 
2513 // end catch_interfaces_capture.h
2514 namespace Catch {
2515 
2516     struct TestFailureException{};
2517     struct AssertionResultData;
2518     struct IResultCapture;
2519     class RunContext;
2520 
2521     class LazyExpression {
2522         friend class AssertionHandler;
2523         friend struct AssertionStats;
2524         friend class RunContext;
2525 
2526         ITransientExpression const* m_transientExpression = nullptr;
2527         bool m_isNegated;
2528     public:
2529         LazyExpression( bool isNegated );
2530         LazyExpression( LazyExpression const& other );
2531         LazyExpression& operator = ( LazyExpression const& ) = delete;
2532 
2533         explicit operator bool() const;
2534 
2535         friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2536     };
2537 
2538     struct AssertionReaction {
2539         bool shouldDebugBreak = false;
2540         bool shouldThrow = false;
2541     };
2542 
2543     class AssertionHandler {
2544         AssertionInfo m_assertionInfo;
2545         AssertionReaction m_reaction;
2546         bool m_completed = false;
2547         IResultCapture& m_resultCapture;
2548 
2549     public:
2550         AssertionHandler
2551             (   StringRef const& macroName,
2552                 SourceLineInfo const& lineInfo,
2553                 StringRef capturedExpression,
2554                 ResultDisposition::Flags resultDisposition );
~AssertionHandler()2555         ~AssertionHandler() {
2556             if ( !m_completed ) {
2557                 m_resultCapture.handleIncomplete( m_assertionInfo );
2558             }
2559         }
2560 
2561         template<typename T>
handleExpr(ExprLhs<T> const & expr)2562         void handleExpr( ExprLhs<T> const& expr ) {
2563             handleExpr( expr.makeUnaryExpr() );
2564         }
2565         void handleExpr( ITransientExpression const& expr );
2566 
2567         void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2568 
2569         void handleExceptionThrownAsExpected();
2570         void handleUnexpectedExceptionNotThrown();
2571         void handleExceptionNotThrownAsExpected();
2572         void handleThrowingCallSkipped();
2573         void handleUnexpectedInflightException();
2574 
2575         void complete();
2576         void setCompleted();
2577 
2578         // query
2579         auto allowThrows() const -> bool;
2580     };
2581 
2582     void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2583 
2584 } // namespace Catch
2585 
2586 // end catch_assertionhandler.h
2587 // start catch_message.h
2588 
2589 #include <string>
2590 #include <vector>
2591 
2592 namespace Catch {
2593 
2594     struct MessageInfo {
2595         MessageInfo(    StringRef const& _macroName,
2596                         SourceLineInfo const& _lineInfo,
2597                         ResultWas::OfType _type );
2598 
2599         StringRef macroName;
2600         std::string message;
2601         SourceLineInfo lineInfo;
2602         ResultWas::OfType type;
2603         unsigned int sequence;
2604 
2605         bool operator == ( MessageInfo const& other ) const;
2606         bool operator < ( MessageInfo const& other ) const;
2607     private:
2608         static unsigned int globalCount;
2609     };
2610 
2611     struct MessageStream {
2612 
2613         template<typename T>
operator <<Catch::MessageStream2614         MessageStream& operator << ( T const& value ) {
2615             m_stream << value;
2616             return *this;
2617         }
2618 
2619         ReusableStringStream m_stream;
2620     };
2621 
2622     struct MessageBuilder : MessageStream {
2623         MessageBuilder( StringRef const& macroName,
2624                         SourceLineInfo const& lineInfo,
2625                         ResultWas::OfType type );
2626 
2627         template<typename T>
operator <<Catch::MessageBuilder2628         MessageBuilder& operator << ( T const& value ) {
2629             m_stream << value;
2630             return *this;
2631         }
2632 
2633         MessageInfo m_info;
2634     };
2635 
2636     class ScopedMessage {
2637     public:
2638         explicit ScopedMessage( MessageBuilder const& builder );
2639         ScopedMessage( ScopedMessage& duplicate ) = delete;
2640         ScopedMessage( ScopedMessage&& old );
2641         ~ScopedMessage();
2642 
2643         MessageInfo m_info;
2644         bool m_moved;
2645     };
2646 
2647     class Capturer {
2648         std::vector<MessageInfo> m_messages;
2649         IResultCapture& m_resultCapture = getResultCapture();
2650         size_t m_captured = 0;
2651     public:
2652         Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2653         ~Capturer();
2654 
2655         void captureValue( size_t index, std::string const& value );
2656 
2657         template<typename T>
captureValues(size_t index,T const & value)2658         void captureValues( size_t index, T const& value ) {
2659             captureValue( index, Catch::Detail::stringify( value ) );
2660         }
2661 
2662         template<typename T, typename... Ts>
captureValues(size_t index,T const & value,Ts const &...values)2663         void captureValues( size_t index, T const& value, Ts const&... values ) {
2664             captureValue( index, Catch::Detail::stringify(value) );
2665             captureValues( index+1, values... );
2666         }
2667     };
2668 
2669 } // end namespace Catch
2670 
2671 // end catch_message.h
2672 #if !defined(CATCH_CONFIG_DISABLE)
2673 
2674 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2675   #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2676 #else
2677   #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2678 #endif
2679 
2680 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2681 
2682 ///////////////////////////////////////////////////////////////////////////////
2683 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2684 // macros.
2685 #define INTERNAL_CATCH_TRY
2686 #define INTERNAL_CATCH_CATCH( capturer )
2687 
2688 #else // CATCH_CONFIG_FAST_COMPILE
2689 
2690 #define INTERNAL_CATCH_TRY try
2691 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2692 
2693 #endif
2694 
2695 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2696 
2697 ///////////////////////////////////////////////////////////////////////////////
2698 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2699     do { \
2700         CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2701         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2702         INTERNAL_CATCH_TRY { \
2703             CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2704             CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2705             catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2706             CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2707         } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2708         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2709     } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2710 
2711 ///////////////////////////////////////////////////////////////////////////////
2712 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2713     INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2714     if( Catch::getResultCapture().lastAssertionPassed() )
2715 
2716 ///////////////////////////////////////////////////////////////////////////////
2717 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2718     INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2719     if( !Catch::getResultCapture().lastAssertionPassed() )
2720 
2721 ///////////////////////////////////////////////////////////////////////////////
2722 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2723     do { \
2724         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2725         try { \
2726             static_cast<void>(__VA_ARGS__); \
2727             catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2728         } \
2729         catch( ... ) { \
2730             catchAssertionHandler.handleUnexpectedInflightException(); \
2731         } \
2732         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2733     } while( false )
2734 
2735 ///////////////////////////////////////////////////////////////////////////////
2736 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2737     do { \
2738         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2739         if( catchAssertionHandler.allowThrows() ) \
2740             try { \
2741                 static_cast<void>(__VA_ARGS__); \
2742                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2743             } \
2744             catch( ... ) { \
2745                 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2746             } \
2747         else \
2748             catchAssertionHandler.handleThrowingCallSkipped(); \
2749         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2750     } while( false )
2751 
2752 ///////////////////////////////////////////////////////////////////////////////
2753 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2754     do { \
2755         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2756         if( catchAssertionHandler.allowThrows() ) \
2757             try { \
2758                 static_cast<void>(expr); \
2759                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2760             } \
2761             catch( exceptionType const& ) { \
2762                 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2763             } \
2764             catch( ... ) { \
2765                 catchAssertionHandler.handleUnexpectedInflightException(); \
2766             } \
2767         else \
2768             catchAssertionHandler.handleThrowingCallSkipped(); \
2769         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2770     } while( false )
2771 
2772 ///////////////////////////////////////////////////////////////////////////////
2773 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2774     do { \
2775         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2776         catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2777         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2778     } while( false )
2779 
2780 ///////////////////////////////////////////////////////////////////////////////
2781 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2782     auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2783     varName.captureValues( 0, __VA_ARGS__ )
2784 
2785 ///////////////////////////////////////////////////////////////////////////////
2786 #define INTERNAL_CATCH_INFO( macroName, log ) \
2787     Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2788 
2789 ///////////////////////////////////////////////////////////////////////////////
2790 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2791     Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2792 
2793 ///////////////////////////////////////////////////////////////////////////////
2794 // Although this is matcher-based, it can be used with just a string
2795 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2796     do { \
2797         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2798         if( catchAssertionHandler.allowThrows() ) \
2799             try { \
2800                 static_cast<void>(__VA_ARGS__); \
2801                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2802             } \
2803             catch( ... ) { \
2804                 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2805             } \
2806         else \
2807             catchAssertionHandler.handleThrowingCallSkipped(); \
2808         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2809     } while( false )
2810 
2811 #endif // CATCH_CONFIG_DISABLE
2812 
2813 // end catch_capture.hpp
2814 // start catch_section.h
2815 
2816 // start catch_section_info.h
2817 
2818 // start catch_totals.h
2819 
2820 #include <cstddef>
2821 
2822 namespace Catch {
2823 
2824     struct Counts {
2825         Counts operator - ( Counts const& other ) const;
2826         Counts& operator += ( Counts const& other );
2827 
2828         std::size_t total() const;
2829         bool allPassed() const;
2830         bool allOk() const;
2831 
2832         std::size_t passed = 0;
2833         std::size_t failed = 0;
2834         std::size_t failedButOk = 0;
2835     };
2836 
2837     struct Totals {
2838 
2839         Totals operator - ( Totals const& other ) const;
2840         Totals& operator += ( Totals const& other );
2841 
2842         Totals delta( Totals const& prevTotals ) const;
2843 
2844         int error = 0;
2845         Counts assertions;
2846         Counts testCases;
2847     };
2848 }
2849 
2850 // end catch_totals.h
2851 #include <string>
2852 
2853 namespace Catch {
2854 
2855     struct SectionInfo {
2856         SectionInfo
2857             (   SourceLineInfo const& _lineInfo,
2858                 std::string const& _name );
2859 
2860         // Deprecated
SectionInfoCatch::SectionInfo2861         SectionInfo
2862             (   SourceLineInfo const& _lineInfo,
2863                 std::string const& _name,
2864                 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2865 
2866         std::string name;
2867         std::string description; // !Deprecated: this will always be empty
2868         SourceLineInfo lineInfo;
2869     };
2870 
2871     struct SectionEndInfo {
2872         SectionInfo sectionInfo;
2873         Counts prevAssertions;
2874         double durationInSeconds;
2875     };
2876 
2877 } // end namespace Catch
2878 
2879 // end catch_section_info.h
2880 // start catch_timer.h
2881 
2882 #include <cstdint>
2883 
2884 namespace Catch {
2885 
2886     auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2887     auto getEstimatedClockResolution() -> uint64_t;
2888 
2889     class Timer {
2890         uint64_t m_nanoseconds = 0;
2891     public:
2892         void start();
2893         auto getElapsedNanoseconds() const -> uint64_t;
2894         auto getElapsedMicroseconds() const -> uint64_t;
2895         auto getElapsedMilliseconds() const -> unsigned int;
2896         auto getElapsedSeconds() const -> double;
2897     };
2898 
2899 } // namespace Catch
2900 
2901 // end catch_timer.h
2902 #include <string>
2903 
2904 namespace Catch {
2905 
2906     class Section : NonCopyable {
2907     public:
2908         Section( SectionInfo const& info );
2909         ~Section();
2910 
2911         // This indicates whether the section should be executed or not
2912         explicit operator bool() const;
2913 
2914     private:
2915         SectionInfo m_info;
2916 
2917         std::string m_name;
2918         Counts m_assertions;
2919         bool m_sectionIncluded;
2920         Timer m_timer;
2921     };
2922 
2923 } // end namespace Catch
2924 
2925 #define INTERNAL_CATCH_SECTION( ... ) \
2926     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2927     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2928     if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2929     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2930 
2931 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2932     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2933     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2934     if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2935     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2936 
2937 // end catch_section.h
2938 // start catch_interfaces_exception.h
2939 
2940 // start catch_interfaces_registry_hub.h
2941 
2942 #include <string>
2943 #include <memory>
2944 
2945 namespace Catch {
2946 
2947     class TestCase;
2948     struct ITestCaseRegistry;
2949     struct IExceptionTranslatorRegistry;
2950     struct IExceptionTranslator;
2951     struct IReporterRegistry;
2952     struct IReporterFactory;
2953     struct ITagAliasRegistry;
2954     struct IMutableEnumValuesRegistry;
2955 
2956     class StartupExceptionRegistry;
2957 
2958     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2959 
2960     struct IRegistryHub {
2961         virtual ~IRegistryHub();
2962 
2963         virtual IReporterRegistry const& getReporterRegistry() const = 0;
2964         virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2965         virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2966         virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2967 
2968         virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2969     };
2970 
2971     struct IMutableRegistryHub {
2972         virtual ~IMutableRegistryHub();
2973         virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2974         virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2975         virtual void registerTest( TestCase const& testInfo ) = 0;
2976         virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2977         virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2978         virtual void registerStartupException() noexcept = 0;
2979         virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2980     };
2981 
2982     IRegistryHub const& getRegistryHub();
2983     IMutableRegistryHub& getMutableRegistryHub();
2984     void cleanUp();
2985     std::string translateActiveException();
2986 
2987 }
2988 
2989 // end catch_interfaces_registry_hub.h
2990 #if defined(CATCH_CONFIG_DISABLE)
2991     #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2992         static std::string translatorName( signature )
2993 #endif
2994 
2995 #include <exception>
2996 #include <string>
2997 #include <vector>
2998 
2999 namespace Catch {
3000     using exceptionTranslateFunction = std::string(*)();
3001 
3002     struct IExceptionTranslator;
3003     using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3004 
3005     struct IExceptionTranslator {
3006         virtual ~IExceptionTranslator();
3007         virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
3008     };
3009 
3010     struct IExceptionTranslatorRegistry {
3011         virtual ~IExceptionTranslatorRegistry();
3012 
3013         virtual std::string translateActiveException() const = 0;
3014     };
3015 
3016     class ExceptionTranslatorRegistrar {
3017         template<typename T>
3018         class ExceptionTranslator : public IExceptionTranslator {
3019         public:
3020 
ExceptionTranslator(std::string (* translateFunction)(T &))3021             ExceptionTranslator( std::string(*translateFunction)( T& ) )
3022             : m_translateFunction( translateFunction )
3023             {}
3024 
translate(ExceptionTranslators::const_iterator it,ExceptionTranslators::const_iterator itEnd) const3025             std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
3026 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3027                 return "";
3028 #else
3029                 try {
3030                     if( it == itEnd )
3031                         std::rethrow_exception(std::current_exception());
3032                     else
3033                         return (*it)->translate( it+1, itEnd );
3034                 }
3035                 catch( T& ex ) {
3036                     return m_translateFunction( ex );
3037                 }
3038 #endif
3039             }
3040 
3041         protected:
3042             std::string(*m_translateFunction)( T& );
3043         };
3044 
3045     public:
3046         template<typename T>
ExceptionTranslatorRegistrar(std::string (* translateFunction)(T &))3047         ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3048             getMutableRegistryHub().registerTranslator
3049                 ( new ExceptionTranslator<T>( translateFunction ) );
3050         }
3051     };
3052 }
3053 
3054 ///////////////////////////////////////////////////////////////////////////////
3055 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3056     static std::string translatorName( signature ); \
3057     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3058     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3059     namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3060     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3061     static std::string translatorName( signature )
3062 
3063 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3064 
3065 // end catch_interfaces_exception.h
3066 // start catch_approx.h
3067 
3068 #include <type_traits>
3069 
3070 namespace Catch {
3071 namespace Detail {
3072 
3073     class Approx {
3074     private:
3075         bool equalityComparisonImpl(double other) const;
3076         // Validates the new margin (margin >= 0)
3077         // out-of-line to avoid including stdexcept in the header
3078         void setMargin(double margin);
3079         // Validates the new epsilon (0 < epsilon < 1)
3080         // out-of-line to avoid including stdexcept in the header
3081         void setEpsilon(double epsilon);
3082 
3083     public:
3084         explicit Approx ( double value );
3085 
3086         static Approx custom();
3087 
3088         Approx operator-() const;
3089 
3090         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ()(T const & value)3091         Approx operator()( T const& value ) {
3092             Approx approx( static_cast<double>(value) );
3093             approx.m_epsilon = m_epsilon;
3094             approx.m_margin = m_margin;
3095             approx.m_scale = m_scale;
3096             return approx;
3097         }
3098 
3099         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx(T const & value)3100         explicit Approx( T const& value ): Approx(static_cast<double>(value))
3101         {}
3102 
3103         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(const T & lhs,Approx const & rhs)3104         friend bool operator == ( const T& lhs, Approx const& rhs ) {
3105             auto lhs_v = static_cast<double>(lhs);
3106             return rhs.equalityComparisonImpl(lhs_v);
3107         }
3108 
3109         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator ==(Approx const & lhs,const T & rhs)3110         friend bool operator == ( Approx const& lhs, const T& rhs ) {
3111             return operator==( rhs, lhs );
3112         }
3113 
3114         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(T const & lhs,Approx const & rhs)3115         friend bool operator != ( T const& lhs, Approx const& rhs ) {
3116             return !operator==( lhs, rhs );
3117         }
3118 
3119         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator !=(Approx const & lhs,T const & rhs)3120         friend bool operator != ( Approx const& lhs, T const& rhs ) {
3121             return !operator==( rhs, lhs );
3122         }
3123 
3124         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(T const & lhs,Approx const & rhs)3125         friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3126             return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3127         }
3128 
3129         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator <=(Approx const & lhs,T const & rhs)3130         friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3131             return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3132         }
3133 
3134         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(T const & lhs,Approx const & rhs)3135         friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3136             return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3137         }
3138 
3139         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
operator >=(Approx const & lhs,T const & rhs)3140         friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3141             return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3142         }
3143 
3144         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilon(T const & newEpsilon)3145         Approx& epsilon( T const& newEpsilon ) {
3146             double epsilonAsDouble = static_cast<double>(newEpsilon);
3147             setEpsilon(epsilonAsDouble);
3148             return *this;
3149         }
3150 
3151         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
margin(T const & newMargin)3152         Approx& margin( T const& newMargin ) {
3153             double marginAsDouble = static_cast<double>(newMargin);
3154             setMargin(marginAsDouble);
3155             return *this;
3156         }
3157 
3158         template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scale(T const & newScale)3159         Approx& scale( T const& newScale ) {
3160             m_scale = static_cast<double>(newScale);
3161             return *this;
3162         }
3163 
3164         std::string toString() const;
3165 
3166     private:
3167         double m_epsilon;
3168         double m_margin;
3169         double m_scale;
3170         double m_value;
3171     };
3172 } // end namespace Detail
3173 
3174 namespace literals {
3175     Detail::Approx operator "" _a(long double val);
3176     Detail::Approx operator "" _a(unsigned long long val);
3177 } // end namespace literals
3178 
3179 template<>
3180 struct StringMaker<Catch::Detail::Approx> {
3181     static std::string convert(Catch::Detail::Approx const& value);
3182 };
3183 
3184 } // end namespace Catch
3185 
3186 // end catch_approx.h
3187 // start catch_string_manip.h
3188 
3189 #include <string>
3190 #include <iosfwd>
3191 #include <vector>
3192 
3193 namespace Catch {
3194 
3195     bool startsWith( std::string const& s, std::string const& prefix );
3196     bool startsWith( std::string const& s, char prefix );
3197     bool endsWith( std::string const& s, std::string const& suffix );
3198     bool endsWith( std::string const& s, char suffix );
3199     bool contains( std::string const& s, std::string const& infix );
3200     void toLowerInPlace( std::string& s );
3201     std::string toLower( std::string const& s );
3202     //! Returns a new string without whitespace at the start/end
3203     std::string trim( std::string const& str );
3204     //! Returns a substring of the original ref without whitespace. Beware lifetimes!
3205     StringRef trim(StringRef ref);
3206 
3207     // !!! Be aware, returns refs into original string - make sure original string outlives them
3208     std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3209     bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3210 
3211     struct pluralise {
3212         pluralise( std::size_t count, std::string const& label );
3213 
3214         friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3215 
3216         std::size_t m_count;
3217         std::string m_label;
3218     };
3219 }
3220 
3221 // end catch_string_manip.h
3222 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3223 // start catch_capture_matchers.h
3224 
3225 // start catch_matchers.h
3226 
3227 #include <string>
3228 #include <vector>
3229 
3230 namespace Catch {
3231 namespace Matchers {
3232     namespace Impl {
3233 
3234         template<typename ArgT> struct MatchAllOf;
3235         template<typename ArgT> struct MatchAnyOf;
3236         template<typename ArgT> struct MatchNotOf;
3237 
3238         class MatcherUntypedBase {
3239         public:
3240             MatcherUntypedBase() = default;
3241             MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3242             MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3243             std::string toString() const;
3244 
3245         protected:
3246             virtual ~MatcherUntypedBase();
3247             virtual std::string describe() const = 0;
3248             mutable std::string m_cachedToString;
3249         };
3250 
3251 #ifdef __clang__
3252 #    pragma clang diagnostic push
3253 #    pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3254 #endif
3255 
3256         template<typename ObjectT>
3257         struct MatcherMethod {
3258             virtual bool match( ObjectT const& arg ) const = 0;
3259         };
3260 
3261 #if defined(__OBJC__)
3262         // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3263         // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3264         template<>
3265         struct MatcherMethod<NSString*> {
3266             virtual bool match( NSString* arg ) const = 0;
3267         };
3268 #endif
3269 
3270 #ifdef __clang__
3271 #    pragma clang diagnostic pop
3272 #endif
3273 
3274         template<typename T>
3275         struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3276 
3277             MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3278             MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3279             MatchNotOf<T> operator ! () const;
3280         };
3281 
3282         template<typename ArgT>
3283         struct MatchAllOf : MatcherBase<ArgT> {
matchCatch::Matchers::Impl::MatchAllOf3284             bool match( ArgT const& arg ) const override {
3285                 for( auto matcher : m_matchers ) {
3286                     if (!matcher->match(arg))
3287                         return false;
3288                 }
3289                 return true;
3290             }
describeCatch::Matchers::Impl::MatchAllOf3291             std::string describe() const override {
3292                 std::string description;
3293                 description.reserve( 4 + m_matchers.size()*32 );
3294                 description += "( ";
3295                 bool first = true;
3296                 for( auto matcher : m_matchers ) {
3297                     if( first )
3298                         first = false;
3299                     else
3300                         description += " and ";
3301                     description += matcher->toString();
3302                 }
3303                 description += " )";
3304                 return description;
3305             }
3306 
operator &&Catch::Matchers::Impl::MatchAllOf3307             MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
3308                 auto copy(*this);
3309                 copy.m_matchers.push_back( &other );
3310                 return copy;
3311             }
3312 
3313             std::vector<MatcherBase<ArgT> const*> m_matchers;
3314         };
3315         template<typename ArgT>
3316         struct MatchAnyOf : MatcherBase<ArgT> {
3317 
matchCatch::Matchers::Impl::MatchAnyOf3318             bool match( ArgT const& arg ) const override {
3319                 for( auto matcher : m_matchers ) {
3320                     if (matcher->match(arg))
3321                         return true;
3322                 }
3323                 return false;
3324             }
describeCatch::Matchers::Impl::MatchAnyOf3325             std::string describe() const override {
3326                 std::string description;
3327                 description.reserve( 4 + m_matchers.size()*32 );
3328                 description += "( ";
3329                 bool first = true;
3330                 for( auto matcher : m_matchers ) {
3331                     if( first )
3332                         first = false;
3333                     else
3334                         description += " or ";
3335                     description += matcher->toString();
3336                 }
3337                 description += " )";
3338                 return description;
3339             }
3340 
operator ||Catch::Matchers::Impl::MatchAnyOf3341             MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
3342                 auto copy(*this);
3343                 copy.m_matchers.push_back( &other );
3344                 return copy;
3345             }
3346 
3347             std::vector<MatcherBase<ArgT> const*> m_matchers;
3348         };
3349 
3350         template<typename ArgT>
3351         struct MatchNotOf : MatcherBase<ArgT> {
3352 
MatchNotOfCatch::Matchers::Impl::MatchNotOf3353             MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3354 
matchCatch::Matchers::Impl::MatchNotOf3355             bool match( ArgT const& arg ) const override {
3356                 return !m_underlyingMatcher.match( arg );
3357             }
3358 
describeCatch::Matchers::Impl::MatchNotOf3359             std::string describe() const override {
3360                 return "not " + m_underlyingMatcher.toString();
3361             }
3362             MatcherBase<ArgT> const& m_underlyingMatcher;
3363         };
3364 
3365         template<typename T>
operator &&(MatcherBase const & other) const3366         MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
3367             return MatchAllOf<T>() && *this && other;
3368         }
3369         template<typename T>
operator ||(MatcherBase const & other) const3370         MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3371             return MatchAnyOf<T>() || *this || other;
3372         }
3373         template<typename T>
operator !() const3374         MatchNotOf<T> MatcherBase<T>::operator ! () const {
3375             return MatchNotOf<T>( *this );
3376         }
3377 
3378     } // namespace Impl
3379 
3380 } // namespace Matchers
3381 
3382 using namespace Matchers;
3383 using Matchers::Impl::MatcherBase;
3384 
3385 } // namespace Catch
3386 
3387 // end catch_matchers.h
3388 // start catch_matchers_exception.hpp
3389 
3390 namespace Catch {
3391 namespace Matchers {
3392 namespace Exception {
3393 
3394 class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3395     std::string m_message;
3396 public:
3397 
ExceptionMessageMatcher(std::string const & message)3398     ExceptionMessageMatcher(std::string const& message):
3399         m_message(message)
3400     {}
3401 
3402     bool match(std::exception const& ex) const override;
3403 
3404     std::string describe() const override;
3405 };
3406 
3407 } // namespace Exception
3408 
3409 Exception::ExceptionMessageMatcher Message(std::string const& message);
3410 
3411 } // namespace Matchers
3412 } // namespace Catch
3413 
3414 // end catch_matchers_exception.hpp
3415 // start catch_matchers_floating.h
3416 
3417 namespace Catch {
3418 namespace Matchers {
3419 
3420     namespace Floating {
3421 
3422         enum class FloatingPointKind : uint8_t;
3423 
3424         struct WithinAbsMatcher : MatcherBase<double> {
3425             WithinAbsMatcher(double target, double margin);
3426             bool match(double const& matchee) const override;
3427             std::string describe() const override;
3428         private:
3429             double m_target;
3430             double m_margin;
3431         };
3432 
3433         struct WithinUlpsMatcher : MatcherBase<double> {
3434             WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3435             bool match(double const& matchee) const override;
3436             std::string describe() const override;
3437         private:
3438             double m_target;
3439             uint64_t m_ulps;
3440             FloatingPointKind m_type;
3441         };
3442 
3443         // Given IEEE-754 format for floats and doubles, we can assume
3444         // that float -> double promotion is lossless. Given this, we can
3445         // assume that if we do the standard relative comparison of
3446         // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3447         // the same result if we do this for floats, as if we do this for
3448         // doubles that were promoted from floats.
3449         struct WithinRelMatcher : MatcherBase<double> {
3450             WithinRelMatcher(double target, double epsilon);
3451             bool match(double const& matchee) const override;
3452             std::string describe() const override;
3453         private:
3454             double m_target;
3455             double m_epsilon;
3456         };
3457 
3458     } // namespace Floating
3459 
3460     // The following functions create the actual matcher objects.
3461     // This allows the types to be inferred
3462     Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3463     Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3464     Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3465     Floating::WithinRelMatcher WithinRel(double target, double eps);
3466     // defaults epsilon to 100*numeric_limits<double>::epsilon()
3467     Floating::WithinRelMatcher WithinRel(double target);
3468     Floating::WithinRelMatcher WithinRel(float target, float eps);
3469     // defaults epsilon to 100*numeric_limits<float>::epsilon()
3470     Floating::WithinRelMatcher WithinRel(float target);
3471 
3472 } // namespace Matchers
3473 } // namespace Catch
3474 
3475 // end catch_matchers_floating.h
3476 // start catch_matchers_generic.hpp
3477 
3478 #include <functional>
3479 #include <string>
3480 
3481 namespace Catch {
3482 namespace Matchers {
3483 namespace Generic {
3484 
3485 namespace Detail {
3486     std::string finalizeDescription(const std::string& desc);
3487 }
3488 
3489 template <typename T>
3490 class PredicateMatcher : public MatcherBase<T> {
3491     std::function<bool(T const&)> m_predicate;
3492     std::string m_description;
3493 public:
3494 
PredicateMatcher(std::function<bool (T const &)> const & elem,std::string const & descr)3495     PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3496         :m_predicate(std::move(elem)),
3497         m_description(Detail::finalizeDescription(descr))
3498     {}
3499 
match(T const & item) const3500     bool match( T const& item ) const override {
3501         return m_predicate(item);
3502     }
3503 
describe() const3504     std::string describe() const override {
3505         return m_description;
3506     }
3507 };
3508 
3509 } // namespace Generic
3510 
3511     // The following functions create the actual matcher objects.
3512     // The user has to explicitly specify type to the function, because
3513     // inferring std::function<bool(T const&)> is hard (but possible) and
3514     // requires a lot of TMP.
3515     template<typename T>
Predicate(std::function<bool (T const &)> const & predicate,std::string const & description="")3516     Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3517         return Generic::PredicateMatcher<T>(predicate, description);
3518     }
3519 
3520 } // namespace Matchers
3521 } // namespace Catch
3522 
3523 // end catch_matchers_generic.hpp
3524 // start catch_matchers_string.h
3525 
3526 #include <string>
3527 
3528 namespace Catch {
3529 namespace Matchers {
3530 
3531     namespace StdString {
3532 
3533         struct CasedString
3534         {
3535             CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3536             std::string adjustString( std::string const& str ) const;
3537             std::string caseSensitivitySuffix() const;
3538 
3539             CaseSensitive::Choice m_caseSensitivity;
3540             std::string m_str;
3541         };
3542 
3543         struct StringMatcherBase : MatcherBase<std::string> {
3544             StringMatcherBase( std::string const& operation, CasedString const& comparator );
3545             std::string describe() const override;
3546 
3547             CasedString m_comparator;
3548             std::string m_operation;
3549         };
3550 
3551         struct EqualsMatcher : StringMatcherBase {
3552             EqualsMatcher( CasedString const& comparator );
3553             bool match( std::string const& source ) const override;
3554         };
3555         struct ContainsMatcher : StringMatcherBase {
3556             ContainsMatcher( CasedString const& comparator );
3557             bool match( std::string const& source ) const override;
3558         };
3559         struct StartsWithMatcher : StringMatcherBase {
3560             StartsWithMatcher( CasedString const& comparator );
3561             bool match( std::string const& source ) const override;
3562         };
3563         struct EndsWithMatcher : StringMatcherBase {
3564             EndsWithMatcher( CasedString const& comparator );
3565             bool match( std::string const& source ) const override;
3566         };
3567 
3568         struct RegexMatcher : MatcherBase<std::string> {
3569             RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3570             bool match( std::string const& matchee ) const override;
3571             std::string describe() const override;
3572 
3573         private:
3574             std::string m_regex;
3575             CaseSensitive::Choice m_caseSensitivity;
3576         };
3577 
3578     } // namespace StdString
3579 
3580     // The following functions create the actual matcher objects.
3581     // This allows the types to be inferred
3582 
3583     StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3584     StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3585     StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3586     StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3587     StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3588 
3589 } // namespace Matchers
3590 } // namespace Catch
3591 
3592 // end catch_matchers_string.h
3593 // start catch_matchers_vector.h
3594 
3595 #include <algorithm>
3596 
3597 namespace Catch {
3598 namespace Matchers {
3599 
3600     namespace Vector {
3601         template<typename T, typename Alloc>
3602         struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3603 
ContainsElementMatcherCatch::Matchers::Vector::ContainsElementMatcher3604             ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3605 
matchCatch::Matchers::Vector::ContainsElementMatcher3606             bool match(std::vector<T, Alloc> const &v) const override {
3607                 for (auto const& el : v) {
3608                     if (el == m_comparator) {
3609                         return true;
3610                     }
3611                 }
3612                 return false;
3613             }
3614 
describeCatch::Matchers::Vector::ContainsElementMatcher3615             std::string describe() const override {
3616                 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3617             }
3618 
3619             T const& m_comparator;
3620         };
3621 
3622         template<typename T, typename AllocComp, typename AllocMatch>
3623         struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3624 
ContainsMatcherCatch::Matchers::Vector::ContainsMatcher3625             ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3626 
matchCatch::Matchers::Vector::ContainsMatcher3627             bool match(std::vector<T, AllocMatch> const &v) const override {
3628                 // !TBD: see note in EqualsMatcher
3629                 if (m_comparator.size() > v.size())
3630                     return false;
3631                 for (auto const& comparator : m_comparator) {
3632                     auto present = false;
3633                     for (const auto& el : v) {
3634                         if (el == comparator) {
3635                             present = true;
3636                             break;
3637                         }
3638                     }
3639                     if (!present) {
3640                         return false;
3641                     }
3642                 }
3643                 return true;
3644             }
describeCatch::Matchers::Vector::ContainsMatcher3645             std::string describe() const override {
3646                 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3647             }
3648 
3649             std::vector<T, AllocComp> const& m_comparator;
3650         };
3651 
3652         template<typename T, typename AllocComp, typename AllocMatch>
3653         struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3654 
EqualsMatcherCatch::Matchers::Vector::EqualsMatcher3655             EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3656 
matchCatch::Matchers::Vector::EqualsMatcher3657             bool match(std::vector<T, AllocMatch> const &v) const override {
3658                 // !TBD: This currently works if all elements can be compared using !=
3659                 // - a more general approach would be via a compare template that defaults
3660                 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3661                 // - then just call that directly
3662                 if (m_comparator.size() != v.size())
3663                     return false;
3664                 for (std::size_t i = 0; i < v.size(); ++i)
3665                     if (m_comparator[i] != v[i])
3666                         return false;
3667                 return true;
3668             }
describeCatch::Matchers::Vector::EqualsMatcher3669             std::string describe() const override {
3670                 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3671             }
3672             std::vector<T, AllocComp> const& m_comparator;
3673         };
3674 
3675         template<typename T, typename AllocComp, typename AllocMatch>
3676         struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3677 
ApproxMatcherCatch::Matchers::Vector::ApproxMatcher3678             ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
3679 
matchCatch::Matchers::Vector::ApproxMatcher3680             bool match(std::vector<T, AllocMatch> const &v) const override {
3681                 if (m_comparator.size() != v.size())
3682                     return false;
3683                 for (std::size_t i = 0; i < v.size(); ++i)
3684                     if (m_comparator[i] != approx(v[i]))
3685                         return false;
3686                 return true;
3687             }
describeCatch::Matchers::Vector::ApproxMatcher3688             std::string describe() const override {
3689                 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3690             }
3691             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
epsilonCatch::Matchers::Vector::ApproxMatcher3692             ApproxMatcher& epsilon( T const& newEpsilon ) {
3693                 approx.epsilon(newEpsilon);
3694                 return *this;
3695             }
3696             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
marginCatch::Matchers::Vector::ApproxMatcher3697             ApproxMatcher& margin( T const& newMargin ) {
3698                 approx.margin(newMargin);
3699                 return *this;
3700             }
3701             template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
scaleCatch::Matchers::Vector::ApproxMatcher3702             ApproxMatcher& scale( T const& newScale ) {
3703                 approx.scale(newScale);
3704                 return *this;
3705             }
3706 
3707             std::vector<T, AllocComp> const& m_comparator;
3708             mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3709         };
3710 
3711         template<typename T, typename AllocComp, typename AllocMatch>
3712         struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
UnorderedEqualsMatcherCatch::Matchers::Vector::UnorderedEqualsMatcher3713             UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
matchCatch::Matchers::Vector::UnorderedEqualsMatcher3714             bool match(std::vector<T, AllocMatch> const& vec) const override {
3715                 if (m_target.size() != vec.size()) {
3716                     return false;
3717                 }
3718                 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3719             }
3720 
describeCatch::Matchers::Vector::UnorderedEqualsMatcher3721             std::string describe() const override {
3722                 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3723             }
3724         private:
3725             std::vector<T, AllocComp> const& m_target;
3726         };
3727 
3728     } // namespace Vector
3729 
3730     // The following functions create the actual matcher objects.
3731     // This allows the types to be inferred
3732 
3733     template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Contains(std::vector<T,AllocComp> const & comparator)3734     Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
3735         return Vector::ContainsMatcher<T, AllocComp, AllocMatch>( comparator );
3736     }
3737 
3738     template<typename T, typename Alloc = std::allocator<T>>
VectorContains(T const & comparator)3739     Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
3740         return Vector::ContainsElementMatcher<T, Alloc>( comparator );
3741     }
3742 
3743     template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Equals(std::vector<T,AllocComp> const & comparator)3744     Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
3745         return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3746     }
3747 
3748     template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
Approx(std::vector<T,AllocComp> const & comparator)3749     Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
3750         return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3751     }
3752 
3753     template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
UnorderedEquals(std::vector<T,AllocComp> const & target)3754     Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
3755         return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3756     }
3757 
3758 } // namespace Matchers
3759 } // namespace Catch
3760 
3761 // end catch_matchers_vector.h
3762 namespace Catch {
3763 
3764     template<typename ArgT, typename MatcherT>
3765     class MatchExpr : public ITransientExpression {
3766         ArgT const& m_arg;
3767         MatcherT m_matcher;
3768         StringRef m_matcherString;
3769     public:
MatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3770         MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3771         :   ITransientExpression{ true, matcher.match( arg ) },
3772             m_arg( arg ),
3773             m_matcher( matcher ),
3774             m_matcherString( matcherString )
3775         {}
3776 
streamReconstructedExpression(std::ostream & os) const3777         void streamReconstructedExpression( std::ostream &os ) const override {
3778             auto matcherAsString = m_matcher.toString();
3779             os << Catch::Detail::stringify( m_arg ) << ' ';
3780             if( matcherAsString == Detail::unprintableString )
3781                 os << m_matcherString;
3782             else
3783                 os << matcherAsString;
3784         }
3785     };
3786 
3787     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
3788 
3789     void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  );
3790 
3791     template<typename ArgT, typename MatcherT>
makeMatchExpr(ArgT const & arg,MatcherT const & matcher,StringRef const & matcherString)3792     auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString  ) -> MatchExpr<ArgT, MatcherT> {
3793         return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3794     }
3795 
3796 } // namespace Catch
3797 
3798 ///////////////////////////////////////////////////////////////////////////////
3799 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3800     do { \
3801         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3802         INTERNAL_CATCH_TRY { \
3803             catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3804         } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3805         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3806     } while( false )
3807 
3808 ///////////////////////////////////////////////////////////////////////////////
3809 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3810     do { \
3811         Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3812         if( catchAssertionHandler.allowThrows() ) \
3813             try { \
3814                 static_cast<void>(__VA_ARGS__ ); \
3815                 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3816             } \
3817             catch( exceptionType const& ex ) { \
3818                 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3819             } \
3820             catch( ... ) { \
3821                 catchAssertionHandler.handleUnexpectedInflightException(); \
3822             } \
3823         else \
3824             catchAssertionHandler.handleThrowingCallSkipped(); \
3825         INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3826     } while( false )
3827 
3828 // end catch_capture_matchers.h
3829 #endif
3830 // start catch_generators.hpp
3831 
3832 // start catch_interfaces_generatortracker.h
3833 
3834 
3835 #include <memory>
3836 
3837 namespace Catch {
3838 
3839     namespace Generators {
3840         class GeneratorUntypedBase {
3841         public:
3842             GeneratorUntypedBase() = default;
3843             virtual ~GeneratorUntypedBase();
3844             // Attempts to move the generator to the next element
3845              //
3846              // Returns true iff the move succeeded (and a valid element
3847              // can be retrieved).
3848             virtual bool next() = 0;
3849         };
3850         using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3851 
3852     } // namespace Generators
3853 
3854     struct IGeneratorTracker {
3855         virtual ~IGeneratorTracker();
3856         virtual auto hasGenerator() const -> bool = 0;
3857         virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3858         virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3859     };
3860 
3861 } // namespace Catch
3862 
3863 // end catch_interfaces_generatortracker.h
3864 // start catch_enforce.h
3865 
3866 #include <exception>
3867 
3868 namespace Catch {
3869 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3870     template <typename Ex>
3871     [[noreturn]]
throw_exception(Ex const & e)3872     void throw_exception(Ex const& e) {
3873         throw e;
3874     }
3875 #else // ^^ Exceptions are enabled //  Exceptions are disabled vv
3876     [[noreturn]]
3877     void throw_exception(std::exception const& e);
3878 #endif
3879 
3880     [[noreturn]]
3881     void throw_logic_error(std::string const& msg);
3882     [[noreturn]]
3883     void throw_domain_error(std::string const& msg);
3884     [[noreturn]]
3885     void throw_runtime_error(std::string const& msg);
3886 
3887 } // namespace Catch;
3888 
3889 #define CATCH_MAKE_MSG(...) \
3890     (Catch::ReusableStringStream() << __VA_ARGS__).str()
3891 
3892 #define CATCH_INTERNAL_ERROR(...) \
3893     Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3894 
3895 #define CATCH_ERROR(...) \
3896     Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3897 
3898 #define CATCH_RUNTIME_ERROR(...) \
3899     Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3900 
3901 #define CATCH_ENFORCE( condition, ... ) \
3902     do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3903 
3904 // end catch_enforce.h
3905 #include <memory>
3906 #include <vector>
3907 #include <cassert>
3908 
3909 #include <utility>
3910 #include <exception>
3911 
3912 namespace Catch {
3913 
3914 class GeneratorException : public std::exception {
3915     const char* const m_msg = "";
3916 
3917 public:
GeneratorException(const char * msg)3918     GeneratorException(const char* msg):
3919         m_msg(msg)
3920     {}
3921 
3922     const char* what() const noexcept override final;
3923 };
3924 
3925 namespace Generators {
3926 
3927     // !TBD move this into its own location?
3928     namespace pf{
3929         template<typename T, typename... Args>
make_unique(Args &&...args)3930         std::unique_ptr<T> make_unique( Args&&... args ) {
3931             return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3932         }
3933     }
3934 
3935     template<typename T>
3936     struct IGenerator : GeneratorUntypedBase {
3937         virtual ~IGenerator() = default;
3938 
3939         // Returns the current element of the generator
3940         //
3941         // \Precondition The generator is either freshly constructed,
3942         // or the last call to `next()` returned true
3943         virtual T const& get() const = 0;
3944         using type = T;
3945     };
3946 
3947     template<typename T>
3948     class SingleValueGenerator final : public IGenerator<T> {
3949         T m_value;
3950     public:
SingleValueGenerator(T && value)3951         SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3952 
get() const3953         T const& get() const override {
3954             return m_value;
3955         }
next()3956         bool next() override {
3957             return false;
3958         }
3959     };
3960 
3961     template<typename T>
3962     class FixedValuesGenerator final : public IGenerator<T> {
3963         static_assert(!std::is_same<T, bool>::value,
3964             "FixedValuesGenerator does not support bools because of std::vector<bool>"
3965             "specialization, use SingleValue Generator instead.");
3966         std::vector<T> m_values;
3967         size_t m_idx = 0;
3968     public:
FixedValuesGenerator(std::initializer_list<T> values)3969         FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3970 
get() const3971         T const& get() const override {
3972             return m_values[m_idx];
3973         }
next()3974         bool next() override {
3975             ++m_idx;
3976             return m_idx < m_values.size();
3977         }
3978     };
3979 
3980     template <typename T>
3981     class GeneratorWrapper final {
3982         std::unique_ptr<IGenerator<T>> m_generator;
3983     public:
GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator)3984         GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3985             m_generator(std::move(generator))
3986         {}
get() const3987         T const& get() const {
3988             return m_generator->get();
3989         }
next()3990         bool next() {
3991             return m_generator->next();
3992         }
3993     };
3994 
3995     template <typename T>
value(T && value)3996     GeneratorWrapper<T> value(T&& value) {
3997         return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
3998     }
3999     template <typename T>
values(std::initializer_list<T> values)4000     GeneratorWrapper<T> values(std::initializer_list<T> values) {
4001         return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4002     }
4003 
4004     template<typename T>
4005     class Generators : public IGenerator<T> {
4006         std::vector<GeneratorWrapper<T>> m_generators;
4007         size_t m_current = 0;
4008 
populate(GeneratorWrapper<T> && generator)4009         void populate(GeneratorWrapper<T>&& generator) {
4010             m_generators.emplace_back(std::move(generator));
4011         }
populate(T && val)4012         void populate(T&& val) {
4013             m_generators.emplace_back(value(std::forward<T>(val)));
4014         }
4015         template<typename U>
populate(U && val)4016         void populate(U&& val) {
4017             populate(T(std::forward<U>(val)));
4018         }
4019         template<typename U, typename... Gs>
populate(U && valueOrGenerator,Gs &&...moreGenerators)4020         void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4021             populate(std::forward<U>(valueOrGenerator));
4022             populate(std::forward<Gs>(moreGenerators)...);
4023         }
4024 
4025     public:
4026         template <typename... Gs>
Generators(Gs &&...moreGenerators)4027         Generators(Gs &&... moreGenerators) {
4028             m_generators.reserve(sizeof...(Gs));
4029             populate(std::forward<Gs>(moreGenerators)...);
4030         }
4031 
get() const4032         T const& get() const override {
4033             return m_generators[m_current].get();
4034         }
4035 
next()4036         bool next() override {
4037             if (m_current >= m_generators.size()) {
4038                 return false;
4039             }
4040             const bool current_status = m_generators[m_current].next();
4041             if (!current_status) {
4042                 ++m_current;
4043             }
4044             return m_current < m_generators.size();
4045         }
4046     };
4047 
4048     template<typename... Ts>
table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples)4049     GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
4050         return values<std::tuple<Ts...>>( tuples );
4051     }
4052 
4053     // Tag type to signal that a generator sequence should convert arguments to a specific type
4054     template <typename T>
4055     struct as {};
4056 
4057     template<typename T, typename... Gs>
makeGenerators(GeneratorWrapper<T> && generator,Gs &&...moreGenerators)4058     auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
4059         return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4060     }
4061     template<typename T>
makeGenerators(GeneratorWrapper<T> && generator)4062     auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4063         return Generators<T>(std::move(generator));
4064     }
4065     template<typename T, typename... Gs>
makeGenerators(T && val,Gs &&...moreGenerators)4066     auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4067         return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4068     }
4069     template<typename T, typename U, typename... Gs>
makeGenerators(as<T>,U && val,Gs &&...moreGenerators)4070     auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4071         return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4072     }
4073 
4074     auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
4075 
4076     template<typename L>
4077     // Note: The type after -> is weird, because VS2015 cannot parse
4078     //       the expression used in the typedef inside, when it is in
4079     //       return type. Yeah.
generate(StringRef generatorName,SourceLineInfo const & lineInfo,L const & generatorExpression)4080     auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4081         using UnderlyingType = typename decltype(generatorExpression())::type;
4082 
4083         IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4084         if (!tracker.hasGenerator()) {
4085             tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4086         }
4087 
4088         auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
4089         return generator.get();
4090     }
4091 
4092 } // namespace Generators
4093 } // namespace Catch
4094 
4095 #define GENERATE( ... ) \
4096     Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4097                                  CATCH_INTERNAL_LINEINFO, \
4098                                  [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4099 #define GENERATE_COPY( ... ) \
4100     Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4101                                  CATCH_INTERNAL_LINEINFO, \
4102                                  [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4103 #define GENERATE_REF( ... ) \
4104     Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4105                                  CATCH_INTERNAL_LINEINFO, \
4106                                  [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4107 
4108 // end catch_generators.hpp
4109 // start catch_generators_generic.hpp
4110 
4111 namespace Catch {
4112 namespace Generators {
4113 
4114     template <typename T>
4115     class TakeGenerator : public IGenerator<T> {
4116         GeneratorWrapper<T> m_generator;
4117         size_t m_returned = 0;
4118         size_t m_target;
4119     public:
TakeGenerator(size_t target,GeneratorWrapper<T> && generator)4120         TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4121             m_generator(std::move(generator)),
4122             m_target(target)
4123         {
4124             assert(target != 0 && "Empty generators are not allowed");
4125         }
get() const4126         T const& get() const override {
4127             return m_generator.get();
4128         }
next()4129         bool next() override {
4130             ++m_returned;
4131             if (m_returned >= m_target) {
4132                 return false;
4133             }
4134 
4135             const auto success = m_generator.next();
4136             // If the underlying generator does not contain enough values
4137             // then we cut short as well
4138             if (!success) {
4139                 m_returned = m_target;
4140             }
4141             return success;
4142         }
4143     };
4144 
4145     template <typename T>
take(size_t target,GeneratorWrapper<T> && generator)4146     GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4147         return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4148     }
4149 
4150     template <typename T, typename Predicate>
4151     class FilterGenerator : public IGenerator<T> {
4152         GeneratorWrapper<T> m_generator;
4153         Predicate m_predicate;
4154     public:
4155         template <typename P = Predicate>
FilterGenerator(P && pred,GeneratorWrapper<T> && generator)4156         FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4157             m_generator(std::move(generator)),
4158             m_predicate(std::forward<P>(pred))
4159         {
4160             if (!m_predicate(m_generator.get())) {
4161                 // It might happen that there are no values that pass the
4162                 // filter. In that case we throw an exception.
4163                 auto has_initial_value = next();
4164                 if (!has_initial_value) {
4165                     Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4166                 }
4167             }
4168         }
4169 
get() const4170         T const& get() const override {
4171             return m_generator.get();
4172         }
4173 
next()4174         bool next() override {
4175             bool success = m_generator.next();
4176             if (!success) {
4177                 return false;
4178             }
4179             while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4180             return success;
4181         }
4182     };
4183 
4184     template <typename T, typename Predicate>
filter(Predicate && pred,GeneratorWrapper<T> && generator)4185     GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4186         return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4187     }
4188 
4189     template <typename T>
4190     class RepeatGenerator : public IGenerator<T> {
4191         static_assert(!std::is_same<T, bool>::value,
4192             "RepeatGenerator currently does not support bools"
4193             "because of std::vector<bool> specialization");
4194         GeneratorWrapper<T> m_generator;
4195         mutable std::vector<T> m_returned;
4196         size_t m_target_repeats;
4197         size_t m_current_repeat = 0;
4198         size_t m_repeat_index = 0;
4199     public:
RepeatGenerator(size_t repeats,GeneratorWrapper<T> && generator)4200         RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4201             m_generator(std::move(generator)),
4202             m_target_repeats(repeats)
4203         {
4204             assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4205         }
4206 
get() const4207         T const& get() const override {
4208             if (m_current_repeat == 0) {
4209                 m_returned.push_back(m_generator.get());
4210                 return m_returned.back();
4211             }
4212             return m_returned[m_repeat_index];
4213         }
4214 
next()4215         bool next() override {
4216             // There are 2 basic cases:
4217             // 1) We are still reading the generator
4218             // 2) We are reading our own cache
4219 
4220             // In the first case, we need to poke the underlying generator.
4221             // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4222             if (m_current_repeat == 0) {
4223                 const auto success = m_generator.next();
4224                 if (!success) {
4225                     ++m_current_repeat;
4226                 }
4227                 return m_current_repeat < m_target_repeats;
4228             }
4229 
4230             // In the second case, we need to move indices forward and check that we haven't run up against the end
4231             ++m_repeat_index;
4232             if (m_repeat_index == m_returned.size()) {
4233                 m_repeat_index = 0;
4234                 ++m_current_repeat;
4235             }
4236             return m_current_repeat < m_target_repeats;
4237         }
4238     };
4239 
4240     template <typename T>
repeat(size_t repeats,GeneratorWrapper<T> && generator)4241     GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4242         return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4243     }
4244 
4245     template <typename T, typename U, typename Func>
4246     class MapGenerator : public IGenerator<T> {
4247         // TBD: provide static assert for mapping function, for friendly error message
4248         GeneratorWrapper<U> m_generator;
4249         Func m_function;
4250         // To avoid returning dangling reference, we have to save the values
4251         T m_cache;
4252     public:
4253         template <typename F2 = Func>
MapGenerator(F2 && function,GeneratorWrapper<U> && generator)4254         MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4255             m_generator(std::move(generator)),
4256             m_function(std::forward<F2>(function)),
4257             m_cache(m_function(m_generator.get()))
4258         {}
4259 
get() const4260         T const& get() const override {
4261             return m_cache;
4262         }
next()4263         bool next() override {
4264             const auto success = m_generator.next();
4265             if (success) {
4266                 m_cache = m_function(m_generator.get());
4267             }
4268             return success;
4269         }
4270     };
4271 
4272     template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
map(Func && function,GeneratorWrapper<U> && generator)4273     GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4274         return GeneratorWrapper<T>(
4275             pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4276         );
4277     }
4278 
4279     template <typename T, typename U, typename Func>
map(Func && function,GeneratorWrapper<U> && generator)4280     GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4281         return GeneratorWrapper<T>(
4282             pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4283         );
4284     }
4285 
4286     template <typename T>
4287     class ChunkGenerator final : public IGenerator<std::vector<T>> {
4288         std::vector<T> m_chunk;
4289         size_t m_chunk_size;
4290         GeneratorWrapper<T> m_generator;
4291         bool m_used_up = false;
4292     public:
ChunkGenerator(size_t size,GeneratorWrapper<T> generator)4293         ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4294             m_chunk_size(size), m_generator(std::move(generator))
4295         {
4296             m_chunk.reserve(m_chunk_size);
4297             if (m_chunk_size != 0) {
4298                 m_chunk.push_back(m_generator.get());
4299                 for (size_t i = 1; i < m_chunk_size; ++i) {
4300                     if (!m_generator.next()) {
4301                         Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4302                     }
4303                     m_chunk.push_back(m_generator.get());
4304                 }
4305             }
4306         }
get() const4307         std::vector<T> const& get() const override {
4308             return m_chunk;
4309         }
next()4310         bool next() override {
4311             m_chunk.clear();
4312             for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4313                 if (!m_generator.next()) {
4314                     return false;
4315                 }
4316                 m_chunk.push_back(m_generator.get());
4317             }
4318             return true;
4319         }
4320     };
4321 
4322     template <typename T>
chunk(size_t size,GeneratorWrapper<T> && generator)4323     GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4324         return GeneratorWrapper<std::vector<T>>(
4325             pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4326         );
4327     }
4328 
4329 } // namespace Generators
4330 } // namespace Catch
4331 
4332 // end catch_generators_generic.hpp
4333 // start catch_generators_specific.hpp
4334 
4335 // start catch_context.h
4336 
4337 #include <memory>
4338 
4339 namespace Catch {
4340 
4341     struct IResultCapture;
4342     struct IRunner;
4343     struct IConfig;
4344     struct IMutableContext;
4345 
4346     using IConfigPtr = std::shared_ptr<IConfig const>;
4347 
4348     struct IContext
4349     {
4350         virtual ~IContext();
4351 
4352         virtual IResultCapture* getResultCapture() = 0;
4353         virtual IRunner* getRunner() = 0;
4354         virtual IConfigPtr const& getConfig() const = 0;
4355     };
4356 
4357     struct IMutableContext : IContext
4358     {
4359         virtual ~IMutableContext();
4360         virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4361         virtual void setRunner( IRunner* runner ) = 0;
4362         virtual void setConfig( IConfigPtr const& config ) = 0;
4363 
4364     private:
4365         static IMutableContext *currentContext;
4366         friend IMutableContext& getCurrentMutableContext();
4367         friend void cleanUpContext();
4368         static void createContext();
4369     };
4370 
getCurrentMutableContext()4371     inline IMutableContext& getCurrentMutableContext()
4372     {
4373         if( !IMutableContext::currentContext )
4374             IMutableContext::createContext();
4375         // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4376         return *IMutableContext::currentContext;
4377     }
4378 
getCurrentContext()4379     inline IContext& getCurrentContext()
4380     {
4381         return getCurrentMutableContext();
4382     }
4383 
4384     void cleanUpContext();
4385 
4386     class SimplePcg32;
4387     SimplePcg32& rng();
4388 }
4389 
4390 // end catch_context.h
4391 // start catch_interfaces_config.h
4392 
4393 // start catch_option.hpp
4394 
4395 namespace Catch {
4396 
4397     // An optional type
4398     template<typename T>
4399     class Option {
4400     public:
Option()4401         Option() : nullableValue( nullptr ) {}
Option(T const & _value)4402         Option( T const& _value )
4403         : nullableValue( new( storage ) T( _value ) )
4404         {}
Option(Option const & _other)4405         Option( Option const& _other )
4406         : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4407         {}
4408 
~Option()4409         ~Option() {
4410             reset();
4411         }
4412 
operator =(Option const & _other)4413         Option& operator= ( Option const& _other ) {
4414             if( &_other != this ) {
4415                 reset();
4416                 if( _other )
4417                     nullableValue = new( storage ) T( *_other );
4418             }
4419             return *this;
4420         }
operator =(T const & _value)4421         Option& operator = ( T const& _value ) {
4422             reset();
4423             nullableValue = new( storage ) T( _value );
4424             return *this;
4425         }
4426 
reset()4427         void reset() {
4428             if( nullableValue )
4429                 nullableValue->~T();
4430             nullableValue = nullptr;
4431         }
4432 
operator *()4433         T& operator*() { return *nullableValue; }
operator *() const4434         T const& operator*() const { return *nullableValue; }
operator ->()4435         T* operator->() { return nullableValue; }
operator ->() const4436         const T* operator->() const { return nullableValue; }
4437 
valueOr(T const & defaultValue) const4438         T valueOr( T const& defaultValue ) const {
4439             return nullableValue ? *nullableValue : defaultValue;
4440         }
4441 
some() const4442         bool some() const { return nullableValue != nullptr; }
none() const4443         bool none() const { return nullableValue == nullptr; }
4444 
operator !() const4445         bool operator !() const { return nullableValue == nullptr; }
operator bool() const4446         explicit operator bool() const {
4447             return some();
4448         }
4449 
4450     private:
4451         T *nullableValue;
4452         alignas(alignof(T)) char storage[sizeof(T)];
4453     };
4454 
4455 } // end namespace Catch
4456 
4457 // end catch_option.hpp
4458 #include <chrono>
4459 #include <iosfwd>
4460 #include <string>
4461 #include <vector>
4462 #include <memory>
4463 
4464 namespace Catch {
4465 
4466     enum class Verbosity {
4467         Quiet = 0,
4468         Normal,
4469         High
4470     };
4471 
4472     struct WarnAbout { enum What {
4473         Nothing = 0x00,
4474         NoAssertions = 0x01,
4475         NoTests = 0x02
4476     }; };
4477 
4478     struct ShowDurations { enum OrNot {
4479         DefaultForReporter,
4480         Always,
4481         Never
4482     }; };
4483     struct RunTests { enum InWhatOrder {
4484         InDeclarationOrder,
4485         InLexicographicalOrder,
4486         InRandomOrder
4487     }; };
4488     struct UseColour { enum YesOrNo {
4489         Auto,
4490         Yes,
4491         No
4492     }; };
4493     struct WaitForKeypress { enum When {
4494         Never,
4495         BeforeStart = 1,
4496         BeforeExit = 2,
4497         BeforeStartAndExit = BeforeStart | BeforeExit
4498     }; };
4499 
4500     class TestSpec;
4501 
4502     struct IConfig : NonCopyable {
4503 
4504         virtual ~IConfig();
4505 
4506         virtual bool allowThrows() const = 0;
4507         virtual std::ostream& stream() const = 0;
4508         virtual std::string name() const = 0;
4509         virtual bool includeSuccessfulResults() const = 0;
4510         virtual bool shouldDebugBreak() const = 0;
4511         virtual bool warnAboutMissingAssertions() const = 0;
4512         virtual bool warnAboutNoTests() const = 0;
4513         virtual int abortAfter() const = 0;
4514         virtual bool showInvisibles() const = 0;
4515         virtual ShowDurations::OrNot showDurations() const = 0;
4516         virtual double minDuration() const = 0;
4517         virtual TestSpec const& testSpec() const = 0;
4518         virtual bool hasTestFilters() const = 0;
4519         virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4520         virtual RunTests::InWhatOrder runOrder() const = 0;
4521         virtual unsigned int rngSeed() const = 0;
4522         virtual UseColour::YesOrNo useColour() const = 0;
4523         virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4524         virtual Verbosity verbosity() const = 0;
4525 
4526         virtual bool benchmarkNoAnalysis() const = 0;
4527         virtual int benchmarkSamples() const = 0;
4528         virtual double benchmarkConfidenceInterval() const = 0;
4529         virtual unsigned int benchmarkResamples() const = 0;
4530         virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4531     };
4532 
4533     using IConfigPtr = std::shared_ptr<IConfig const>;
4534 }
4535 
4536 // end catch_interfaces_config.h
4537 // start catch_random_number_generator.h
4538 
4539 #include <cstdint>
4540 
4541 namespace Catch {
4542 
4543     // This is a simple implementation of C++11 Uniform Random Number
4544     // Generator. It does not provide all operators, because Catch2
4545     // does not use it, but it should behave as expected inside stdlib's
4546     // distributions.
4547     // The implementation is based on the PCG family (http://pcg-random.org)
4548     class SimplePcg32 {
4549         using state_type = std::uint64_t;
4550     public:
4551         using result_type = std::uint32_t;
result_type(min)4552         static constexpr result_type (min)() {
4553             return 0;
4554         }
result_type(max)4555         static constexpr result_type (max)() {
4556             return static_cast<result_type>(-1);
4557         }
4558 
4559         // Provide some default initial state for the default constructor
SimplePcg32()4560         SimplePcg32():SimplePcg32(0xed743cc4U) {}
4561 
4562         explicit SimplePcg32(result_type seed_);
4563 
4564         void seed(result_type seed_);
4565         void discard(uint64_t skip);
4566 
4567         result_type operator()();
4568 
4569     private:
4570         friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4571         friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4572 
4573         // In theory we also need operator<< and operator>>
4574         // In practice we do not use them, so we will skip them for now
4575 
4576         std::uint64_t m_state;
4577         // This part of the state determines which "stream" of the numbers
4578         // is chosen -- we take it as a constant for Catch2, so we only
4579         // need to deal with seeding the main state.
4580         // Picked by reading 8 bytes from `/dev/random` :-)
4581         static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4582     };
4583 
4584 } // end namespace Catch
4585 
4586 // end catch_random_number_generator.h
4587 #include <random>
4588 
4589 namespace Catch {
4590 namespace Generators {
4591 
4592 template <typename Float>
4593 class RandomFloatingGenerator final : public IGenerator<Float> {
4594     Catch::SimplePcg32& m_rng;
4595     std::uniform_real_distribution<Float> m_dist;
4596     Float m_current_number;
4597 public:
4598 
RandomFloatingGenerator(Float a,Float b)4599     RandomFloatingGenerator(Float a, Float b):
4600         m_rng(rng()),
4601         m_dist(a, b) {
4602         static_cast<void>(next());
4603     }
4604 
get() const4605     Float const& get() const override {
4606         return m_current_number;
4607     }
next()4608     bool next() override {
4609         m_current_number = m_dist(m_rng);
4610         return true;
4611     }
4612 };
4613 
4614 template <typename Integer>
4615 class RandomIntegerGenerator final : public IGenerator<Integer> {
4616     Catch::SimplePcg32& m_rng;
4617     std::uniform_int_distribution<Integer> m_dist;
4618     Integer m_current_number;
4619 public:
4620 
RandomIntegerGenerator(Integer a,Integer b)4621     RandomIntegerGenerator(Integer a, Integer b):
4622         m_rng(rng()),
4623         m_dist(a, b) {
4624         static_cast<void>(next());
4625     }
4626 
get() const4627     Integer const& get() const override {
4628         return m_current_number;
4629     }
next()4630     bool next() override {
4631         m_current_number = m_dist(m_rng);
4632         return true;
4633     }
4634 };
4635 
4636 // TODO: Ideally this would be also constrained against the various char types,
4637 //       but I don't expect users to run into that in practice.
4638 template <typename T>
4639 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4640 GeneratorWrapper<T>>::type
random(T a,T b)4641 random(T a, T b) {
4642     return GeneratorWrapper<T>(
4643         pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4644     );
4645 }
4646 
4647 template <typename T>
4648 typename std::enable_if<std::is_floating_point<T>::value,
4649 GeneratorWrapper<T>>::type
random(T a,T b)4650 random(T a, T b) {
4651     return GeneratorWrapper<T>(
4652         pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4653     );
4654 }
4655 
4656 template <typename T>
4657 class RangeGenerator final : public IGenerator<T> {
4658     T m_current;
4659     T m_end;
4660     T m_step;
4661     bool m_positive;
4662 
4663 public:
RangeGenerator(T const & start,T const & end,T const & step)4664     RangeGenerator(T const& start, T const& end, T const& step):
4665         m_current(start),
4666         m_end(end),
4667         m_step(step),
4668         m_positive(m_step > T(0))
4669     {
4670         assert(m_current != m_end && "Range start and end cannot be equal");
4671         assert(m_step != T(0) && "Step size cannot be zero");
4672         assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4673     }
4674 
RangeGenerator(T const & start,T const & end)4675     RangeGenerator(T const& start, T const& end):
4676         RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4677     {}
4678 
get() const4679     T const& get() const override {
4680         return m_current;
4681     }
4682 
next()4683     bool next() override {
4684         m_current += m_step;
4685         return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4686     }
4687 };
4688 
4689 template <typename T>
range(T const & start,T const & end,T const & step)4690 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4691     static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
4692     return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4693 }
4694 
4695 template <typename T>
range(T const & start,T const & end)4696 GeneratorWrapper<T> range(T const& start, T const& end) {
4697     static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4698     return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4699 }
4700 
4701 template <typename T>
4702 class IteratorGenerator final : public IGenerator<T> {
4703     static_assert(!std::is_same<T, bool>::value,
4704         "IteratorGenerator currently does not support bools"
4705         "because of std::vector<bool> specialization");
4706 
4707     std::vector<T> m_elems;
4708     size_t m_current = 0;
4709 public:
4710     template <typename InputIterator, typename InputSentinel>
IteratorGenerator(InputIterator first,InputSentinel last)4711     IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4712         if (m_elems.empty()) {
4713             Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
4714         }
4715     }
4716 
get() const4717     T const& get() const override {
4718         return m_elems[m_current];
4719     }
4720 
next()4721     bool next() override {
4722         ++m_current;
4723         return m_current != m_elems.size();
4724     }
4725 };
4726 
4727 template <typename InputIterator,
4728           typename InputSentinel,
4729           typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
from_range(InputIterator from,InputSentinel to)4730 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4731     return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4732 }
4733 
4734 template <typename Container,
4735           typename ResultType = typename Container::value_type>
from_range(Container const & cnt)4736 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4737     return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4738 }
4739 
4740 } // namespace Generators
4741 } // namespace Catch
4742 
4743 // end catch_generators_specific.hpp
4744 
4745 // These files are included here so the single_include script doesn't put them
4746 // in the conditionally compiled sections
4747 // start catch_test_case_info.h
4748 
4749 #include <string>
4750 #include <vector>
4751 #include <memory>
4752 
4753 #ifdef __clang__
4754 #pragma clang diagnostic push
4755 #pragma clang diagnostic ignored "-Wpadded"
4756 #endif
4757 
4758 namespace Catch {
4759 
4760     struct ITestInvoker;
4761 
4762     struct TestCaseInfo {
4763         enum SpecialProperties{
4764             None = 0,
4765             IsHidden = 1 << 1,
4766             ShouldFail = 1 << 2,
4767             MayFail = 1 << 3,
4768             Throws = 1 << 4,
4769             NonPortable = 1 << 5,
4770             Benchmark = 1 << 6
4771         };
4772 
4773         TestCaseInfo(   std::string const& _name,
4774                         std::string const& _className,
4775                         std::string const& _description,
4776                         std::vector<std::string> const& _tags,
4777                         SourceLineInfo const& _lineInfo );
4778 
4779         friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4780 
4781         bool isHidden() const;
4782         bool throws() const;
4783         bool okToFail() const;
4784         bool expectedToFail() const;
4785 
4786         std::string tagsAsString() const;
4787 
4788         std::string name;
4789         std::string className;
4790         std::string description;
4791         std::vector<std::string> tags;
4792         std::vector<std::string> lcaseTags;
4793         SourceLineInfo lineInfo;
4794         SpecialProperties properties;
4795     };
4796 
4797     class TestCase : public TestCaseInfo {
4798     public:
4799 
4800         TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4801 
4802         TestCase withName( std::string const& _newName ) const;
4803 
4804         void invoke() const;
4805 
4806         TestCaseInfo const& getTestCaseInfo() const;
4807 
4808         bool operator == ( TestCase const& other ) const;
4809         bool operator < ( TestCase const& other ) const;
4810 
4811     private:
4812         std::shared_ptr<ITestInvoker> test;
4813     };
4814 
4815     TestCase makeTestCase(  ITestInvoker* testCase,
4816                             std::string const& className,
4817                             NameAndTags const& nameAndTags,
4818                             SourceLineInfo const& lineInfo );
4819 }
4820 
4821 #ifdef __clang__
4822 #pragma clang diagnostic pop
4823 #endif
4824 
4825 // end catch_test_case_info.h
4826 // start catch_interfaces_runner.h
4827 
4828 namespace Catch {
4829 
4830     struct IRunner {
4831         virtual ~IRunner();
4832         virtual bool aborting() const = 0;
4833     };
4834 }
4835 
4836 // end catch_interfaces_runner.h
4837 
4838 #ifdef __OBJC__
4839 // start catch_objc.hpp
4840 
4841 #import <objc/runtime.h>
4842 
4843 #include <string>
4844 
4845 // NB. Any general catch headers included here must be included
4846 // in catch.hpp first to make sure they are included by the single
4847 // header for non obj-usage
4848 
4849 ///////////////////////////////////////////////////////////////////////////////
4850 // This protocol is really only here for (self) documenting purposes, since
4851 // all its methods are optional.
4852 @protocol OcFixture
4853 
4854 @optional
4855 
4856 -(void) setUp;
4857 -(void) tearDown;
4858 
4859 @end
4860 
4861 namespace Catch {
4862 
4863     class OcMethod : public ITestInvoker {
4864 
4865     public:
OcMethod(Class cls,SEL sel)4866         OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4867 
invoke() const4868         virtual void invoke() const {
4869             id obj = [[m_cls alloc] init];
4870 
4871             performOptionalSelector( obj, @selector(setUp)  );
4872             performOptionalSelector( obj, m_sel );
4873             performOptionalSelector( obj, @selector(tearDown)  );
4874 
4875             arcSafeRelease( obj );
4876         }
4877     private:
~OcMethod()4878         virtual ~OcMethod() {}
4879 
4880         Class m_cls;
4881         SEL m_sel;
4882     };
4883 
4884     namespace Detail{
4885 
getAnnotation(Class cls,std::string const & annotationName,std::string const & testCaseName)4886         inline std::string getAnnotation(   Class cls,
4887                                             std::string const& annotationName,
4888                                             std::string const& testCaseName ) {
4889             NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4890             SEL sel = NSSelectorFromString( selStr );
4891             arcSafeRelease( selStr );
4892             id value = performOptionalSelector( cls, sel );
4893             if( value )
4894                 return [(NSString*)value UTF8String];
4895             return "";
4896         }
4897     }
4898 
registerTestMethods()4899     inline std::size_t registerTestMethods() {
4900         std::size_t noTestMethods = 0;
4901         int noClasses = objc_getClassList( nullptr, 0 );
4902 
4903         Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4904         objc_getClassList( classes, noClasses );
4905 
4906         for( int c = 0; c < noClasses; c++ ) {
4907             Class cls = classes[c];
4908             {
4909                 u_int count;
4910                 Method* methods = class_copyMethodList( cls, &count );
4911                 for( u_int m = 0; m < count ; m++ ) {
4912                     SEL selector = method_getName(methods[m]);
4913                     std::string methodName = sel_getName(selector);
4914                     if( startsWith( methodName, "Catch_TestCase_" ) ) {
4915                         std::string testCaseName = methodName.substr( 15 );
4916                         std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4917                         std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4918                         const char* className = class_getName( cls );
4919 
4920                         getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4921                         noTestMethods++;
4922                     }
4923                 }
4924                 free(methods);
4925             }
4926         }
4927         return noTestMethods;
4928     }
4929 
4930 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4931 
4932     namespace Matchers {
4933         namespace Impl {
4934         namespace NSStringMatchers {
4935 
4936             struct StringHolder : MatcherBase<NSString*>{
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4937                 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4938                 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
StringHolderCatch::Matchers::Impl::NSStringMatchers::StringHolder4939                 StringHolder() {
4940                     arcSafeRelease( m_substr );
4941                 }
4942 
matchCatch::Matchers::Impl::NSStringMatchers::StringHolder4943                 bool match( NSString* str ) const override {
4944                     return false;
4945                 }
4946 
4947                 NSString* CATCH_ARC_STRONG m_substr;
4948             };
4949 
4950             struct Equals : StringHolder {
EqualsCatch::Matchers::Impl::NSStringMatchers::Equals4951                 Equals( NSString* substr ) : StringHolder( substr ){}
4952 
matchCatch::Matchers::Impl::NSStringMatchers::Equals4953                 bool match( NSString* str ) const override {
4954                     return  (str != nil || m_substr == nil ) &&
4955                             [str isEqualToString:m_substr];
4956                 }
4957 
describeCatch::Matchers::Impl::NSStringMatchers::Equals4958                 std::string describe() const override {
4959                     return "equals string: " + Catch::Detail::stringify( m_substr );
4960                 }
4961             };
4962 
4963             struct Contains : StringHolder {
ContainsCatch::Matchers::Impl::NSStringMatchers::Contains4964                 Contains( NSString* substr ) : StringHolder( substr ){}
4965 
matchCatch::Matchers::Impl::NSStringMatchers::Contains4966                 bool match( NSString* str ) const override {
4967                     return  (str != nil || m_substr == nil ) &&
4968                             [str rangeOfString:m_substr].location != NSNotFound;
4969                 }
4970 
describeCatch::Matchers::Impl::NSStringMatchers::Contains4971                 std::string describe() const override {
4972                     return "contains string: " + Catch::Detail::stringify( m_substr );
4973                 }
4974             };
4975 
4976             struct StartsWith : StringHolder {
StartsWithCatch::Matchers::Impl::NSStringMatchers::StartsWith4977                 StartsWith( NSString* substr ) : StringHolder( substr ){}
4978 
matchCatch::Matchers::Impl::NSStringMatchers::StartsWith4979                 bool match( NSString* str ) const override {
4980                     return  (str != nil || m_substr == nil ) &&
4981                             [str rangeOfString:m_substr].location == 0;
4982                 }
4983 
describeCatch::Matchers::Impl::NSStringMatchers::StartsWith4984                 std::string describe() const override {
4985                     return "starts with: " + Catch::Detail::stringify( m_substr );
4986                 }
4987             };
4988             struct EndsWith : StringHolder {
EndsWithCatch::Matchers::Impl::NSStringMatchers::EndsWith4989                 EndsWith( NSString* substr ) : StringHolder( substr ){}
4990 
matchCatch::Matchers::Impl::NSStringMatchers::EndsWith4991                 bool match( NSString* str ) const override {
4992                     return  (str != nil || m_substr == nil ) &&
4993                             [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4994                 }
4995 
describeCatch::Matchers::Impl::NSStringMatchers::EndsWith4996                 std::string describe() const override {
4997                     return "ends with: " + Catch::Detail::stringify( m_substr );
4998                 }
4999             };
5000 
5001         } // namespace NSStringMatchers
5002         } // namespace Impl
5003 
5004         inline Impl::NSStringMatchers::Equals
Equals(NSString * substr)5005             Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
5006 
5007         inline Impl::NSStringMatchers::Contains
Contains(NSString * substr)5008             Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
5009 
5010         inline Impl::NSStringMatchers::StartsWith
StartsWith(NSString * substr)5011             StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
5012 
5013         inline Impl::NSStringMatchers::EndsWith
EndsWith(NSString * substr)5014             EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
5015 
5016     } // namespace Matchers
5017 
5018     using namespace Matchers;
5019 
5020 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5021 
5022 } // namespace Catch
5023 
5024 ///////////////////////////////////////////////////////////////////////////////
5025 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5026 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5027 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5028 { \
5029 return @ name; \
5030 } \
5031 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5032 { \
5033 return @ desc; \
5034 } \
5035 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5036 
5037 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5038 
5039 // end catch_objc.hpp
5040 #endif
5041 
5042 // Benchmarking needs the externally-facing parts of reporters to work
5043 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5044 // start catch_external_interfaces.h
5045 
5046 // start catch_reporter_bases.hpp
5047 
5048 // start catch_interfaces_reporter.h
5049 
5050 // start catch_config.hpp
5051 
5052 // start catch_test_spec_parser.h
5053 
5054 #ifdef __clang__
5055 #pragma clang diagnostic push
5056 #pragma clang diagnostic ignored "-Wpadded"
5057 #endif
5058 
5059 // start catch_test_spec.h
5060 
5061 #ifdef __clang__
5062 #pragma clang diagnostic push
5063 #pragma clang diagnostic ignored "-Wpadded"
5064 #endif
5065 
5066 // start catch_wildcard_pattern.h
5067 
5068 namespace Catch
5069 {
5070     class WildcardPattern {
5071         enum WildcardPosition {
5072             NoWildcard = 0,
5073             WildcardAtStart = 1,
5074             WildcardAtEnd = 2,
5075             WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5076         };
5077 
5078     public:
5079 
5080         WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
5081         virtual ~WildcardPattern() = default;
5082         virtual bool matches( std::string const& str ) const;
5083 
5084     private:
5085         std::string normaliseString( std::string const& str ) const;
5086         CaseSensitive::Choice m_caseSensitivity;
5087         WildcardPosition m_wildcard = NoWildcard;
5088         std::string m_pattern;
5089     };
5090 }
5091 
5092 // end catch_wildcard_pattern.h
5093 #include <string>
5094 #include <vector>
5095 #include <memory>
5096 
5097 namespace Catch {
5098 
5099     struct IConfig;
5100 
5101     class TestSpec {
5102         class Pattern {
5103         public:
5104             explicit Pattern( std::string const& name );
5105             virtual ~Pattern();
5106             virtual bool matches( TestCaseInfo const& testCase ) const = 0;
5107             std::string const& name() const;
5108         private:
5109             std::string const m_name;
5110         };
5111         using PatternPtr = std::shared_ptr<Pattern>;
5112 
5113         class NamePattern : public Pattern {
5114         public:
5115             explicit NamePattern( std::string const& name, std::string const& filterString );
5116             bool matches( TestCaseInfo const& testCase ) const override;
5117         private:
5118             WildcardPattern m_wildcardPattern;
5119         };
5120 
5121         class TagPattern : public Pattern {
5122         public:
5123             explicit TagPattern( std::string const& tag, std::string const& filterString );
5124             bool matches( TestCaseInfo const& testCase ) const override;
5125         private:
5126             std::string m_tag;
5127         };
5128 
5129         class ExcludedPattern : public Pattern {
5130         public:
5131             explicit ExcludedPattern( PatternPtr const& underlyingPattern );
5132             bool matches( TestCaseInfo const& testCase ) const override;
5133         private:
5134             PatternPtr m_underlyingPattern;
5135         };
5136 
5137         struct Filter {
5138             std::vector<PatternPtr> m_patterns;
5139 
5140             bool matches( TestCaseInfo const& testCase ) const;
5141             std::string name() const;
5142         };
5143 
5144     public:
5145         struct FilterMatch {
5146             std::string name;
5147             std::vector<TestCase const*> tests;
5148         };
5149         using Matches = std::vector<FilterMatch>;
5150         using vectorStrings = std::vector<std::string>;
5151 
5152         bool hasFilters() const;
5153         bool matches( TestCaseInfo const& testCase ) const;
5154         Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
5155         const vectorStrings & getInvalidArgs() const;
5156 
5157     private:
5158         std::vector<Filter> m_filters;
5159         std::vector<std::string> m_invalidArgs;
5160         friend class TestSpecParser;
5161     };
5162 }
5163 
5164 #ifdef __clang__
5165 #pragma clang diagnostic pop
5166 #endif
5167 
5168 // end catch_test_spec.h
5169 // start catch_interfaces_tag_alias_registry.h
5170 
5171 #include <string>
5172 
5173 namespace Catch {
5174 
5175     struct TagAlias;
5176 
5177     struct ITagAliasRegistry {
5178         virtual ~ITagAliasRegistry();
5179         // Nullptr if not present
5180         virtual TagAlias const* find( std::string const& alias ) const = 0;
5181         virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
5182 
5183         static ITagAliasRegistry const& get();
5184     };
5185 
5186 } // end namespace Catch
5187 
5188 // end catch_interfaces_tag_alias_registry.h
5189 namespace Catch {
5190 
5191     class TestSpecParser {
5192         enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5193         Mode m_mode = None;
5194         Mode lastMode = None;
5195         bool m_exclusion = false;
5196         std::size_t m_pos = 0;
5197         std::size_t m_realPatternPos = 0;
5198         std::string m_arg;
5199         std::string m_substring;
5200         std::string m_patternName;
5201         std::vector<std::size_t> m_escapeChars;
5202         TestSpec::Filter m_currentFilter;
5203         TestSpec m_testSpec;
5204         ITagAliasRegistry const* m_tagAliases = nullptr;
5205 
5206     public:
5207         TestSpecParser( ITagAliasRegistry const& tagAliases );
5208 
5209         TestSpecParser& parse( std::string const& arg );
5210         TestSpec testSpec();
5211 
5212     private:
5213         bool visitChar( char c );
5214         void startNewMode( Mode mode );
5215         bool processNoneChar( char c );
5216         void processNameChar( char c );
5217         bool processOtherChar( char c );
5218         void endMode();
5219         void escape();
5220         bool isControlChar( char c ) const;
5221         void saveLastMode();
5222         void revertBackToLastMode();
5223         void addFilter();
5224         bool separate();
5225 
5226         // Handles common preprocessing of the pattern for name/tag patterns
5227         std::string preprocessPattern();
5228         // Adds the current pattern as a test name
5229         void addNamePattern();
5230         // Adds the current pattern as a tag
5231         void addTagPattern();
5232 
addCharToPattern(char c)5233         inline void addCharToPattern(char c) {
5234             m_substring += c;
5235             m_patternName += c;
5236             m_realPatternPos++;
5237         }
5238 
5239     };
5240     TestSpec parseTestSpec( std::string const& arg );
5241 
5242 } // namespace Catch
5243 
5244 #ifdef __clang__
5245 #pragma clang diagnostic pop
5246 #endif
5247 
5248 // end catch_test_spec_parser.h
5249 // Libstdc++ doesn't like incomplete classes for unique_ptr
5250 
5251 #include <memory>
5252 #include <vector>
5253 #include <string>
5254 
5255 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5256 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5257 #endif
5258 
5259 namespace Catch {
5260 
5261     struct IStream;
5262 
5263     struct ConfigData {
5264         bool listTests = false;
5265         bool listTags = false;
5266         bool listReporters = false;
5267         bool listTestNamesOnly = false;
5268 
5269         bool showSuccessfulTests = false;
5270         bool shouldDebugBreak = false;
5271         bool noThrow = false;
5272         bool showHelp = false;
5273         bool showInvisibles = false;
5274         bool filenamesAsTags = false;
5275         bool libIdentify = false;
5276 
5277         int abortAfter = -1;
5278         unsigned int rngSeed = 0;
5279 
5280         bool benchmarkNoAnalysis = false;
5281         unsigned int benchmarkSamples = 100;
5282         double benchmarkConfidenceInterval = 0.95;
5283         unsigned int benchmarkResamples = 100000;
5284         std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5285 
5286         Verbosity verbosity = Verbosity::Normal;
5287         WarnAbout::What warnings = WarnAbout::Nothing;
5288         ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5289         double minDuration = -1;
5290         RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5291         UseColour::YesOrNo useColour = UseColour::Auto;
5292         WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5293 
5294         std::string outputFilename;
5295         std::string name;
5296         std::string processName;
5297 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5298 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5299 #endif
5300         std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5301 #undef CATCH_CONFIG_DEFAULT_REPORTER
5302 
5303         std::vector<std::string> testsOrTags;
5304         std::vector<std::string> sectionsToRun;
5305     };
5306 
5307     class Config : public IConfig {
5308     public:
5309 
5310         Config() = default;
5311         Config( ConfigData const& data );
5312         virtual ~Config() = default;
5313 
5314         std::string const& getFilename() const;
5315 
5316         bool listTests() const;
5317         bool listTestNamesOnly() const;
5318         bool listTags() const;
5319         bool listReporters() const;
5320 
5321         std::string getProcessName() const;
5322         std::string const& getReporterName() const;
5323 
5324         std::vector<std::string> const& getTestsOrTags() const override;
5325         std::vector<std::string> const& getSectionsToRun() const override;
5326 
5327         TestSpec const& testSpec() const override;
5328         bool hasTestFilters() const override;
5329 
5330         bool showHelp() const;
5331 
5332         // IConfig interface
5333         bool allowThrows() const override;
5334         std::ostream& stream() const override;
5335         std::string name() const override;
5336         bool includeSuccessfulResults() const override;
5337         bool warnAboutMissingAssertions() const override;
5338         bool warnAboutNoTests() const override;
5339         ShowDurations::OrNot showDurations() const override;
5340         double minDuration() const override;
5341         RunTests::InWhatOrder runOrder() const override;
5342         unsigned int rngSeed() const override;
5343         UseColour::YesOrNo useColour() const override;
5344         bool shouldDebugBreak() const override;
5345         int abortAfter() const override;
5346         bool showInvisibles() const override;
5347         Verbosity verbosity() const override;
5348         bool benchmarkNoAnalysis() const override;
5349         int benchmarkSamples() const override;
5350         double benchmarkConfidenceInterval() const override;
5351         unsigned int benchmarkResamples() const override;
5352         std::chrono::milliseconds benchmarkWarmupTime() const override;
5353 
5354     private:
5355 
5356         IStream const* openStream();
5357         ConfigData m_data;
5358 
5359         std::unique_ptr<IStream const> m_stream;
5360         TestSpec m_testSpec;
5361         bool m_hasTestFilters = false;
5362     };
5363 
5364 } // end namespace Catch
5365 
5366 // end catch_config.hpp
5367 // start catch_assertionresult.h
5368 
5369 #include <string>
5370 
5371 namespace Catch {
5372 
5373     struct AssertionResultData
5374     {
5375         AssertionResultData() = delete;
5376 
5377         AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5378 
5379         std::string message;
5380         mutable std::string reconstructedExpression;
5381         LazyExpression lazyExpression;
5382         ResultWas::OfType resultType;
5383 
5384         std::string reconstructExpression() const;
5385     };
5386 
5387     class AssertionResult {
5388     public:
5389         AssertionResult() = delete;
5390         AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5391 
5392         bool isOk() const;
5393         bool succeeded() const;
5394         ResultWas::OfType getResultType() const;
5395         bool hasExpression() const;
5396         bool hasMessage() const;
5397         std::string getExpression() const;
5398         std::string getExpressionInMacro() const;
5399         bool hasExpandedExpression() const;
5400         std::string getExpandedExpression() const;
5401         std::string getMessage() const;
5402         SourceLineInfo getSourceInfo() const;
5403         StringRef getTestMacroName() const;
5404 
5405     //protected:
5406         AssertionInfo m_info;
5407         AssertionResultData m_resultData;
5408     };
5409 
5410 } // end namespace Catch
5411 
5412 // end catch_assertionresult.h
5413 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5414 // start catch_estimate.hpp
5415 
5416  // Statistics estimates
5417 
5418 
5419 namespace Catch {
5420     namespace Benchmark {
5421         template <typename Duration>
5422         struct Estimate {
5423             Duration point;
5424             Duration lower_bound;
5425             Duration upper_bound;
5426             double confidence_interval;
5427 
5428             template <typename Duration2>
operator Estimate<Duration2>Catch::Benchmark::Estimate5429             operator Estimate<Duration2>() const {
5430                 return { point, lower_bound, upper_bound, confidence_interval };
5431             }
5432         };
5433     } // namespace Benchmark
5434 } // namespace Catch
5435 
5436 // end catch_estimate.hpp
5437 // start catch_outlier_classification.hpp
5438 
5439 // Outlier information
5440 
5441 namespace Catch {
5442     namespace Benchmark {
5443         struct OutlierClassification {
5444             int samples_seen = 0;
5445             int low_severe = 0;     // more than 3 times IQR below Q1
5446             int low_mild = 0;       // 1.5 to 3 times IQR below Q1
5447             int high_mild = 0;      // 1.5 to 3 times IQR above Q3
5448             int high_severe = 0;    // more than 3 times IQR above Q3
5449 
totalCatch::Benchmark::OutlierClassification5450             int total() const {
5451                 return low_severe + low_mild + high_mild + high_severe;
5452             }
5453         };
5454     } // namespace Benchmark
5455 } // namespace Catch
5456 
5457 // end catch_outlier_classification.hpp
5458 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5459 
5460 #include <string>
5461 #include <iosfwd>
5462 #include <map>
5463 #include <set>
5464 #include <memory>
5465 #include <algorithm>
5466 
5467 namespace Catch {
5468 
5469     struct ReporterConfig {
5470         explicit ReporterConfig( IConfigPtr const& _fullConfig );
5471 
5472         ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5473 
5474         std::ostream& stream() const;
5475         IConfigPtr fullConfig() const;
5476 
5477     private:
5478         std::ostream* m_stream;
5479         IConfigPtr m_fullConfig;
5480     };
5481 
5482     struct ReporterPreferences {
5483         bool shouldRedirectStdOut = false;
5484         bool shouldReportAllAssertions = false;
5485     };
5486 
5487     template<typename T>
5488     struct LazyStat : Option<T> {
operator =Catch::LazyStat5489         LazyStat& operator=( T const& _value ) {
5490             Option<T>::operator=( _value );
5491             used = false;
5492             return *this;
5493         }
resetCatch::LazyStat5494         void reset() {
5495             Option<T>::reset();
5496             used = false;
5497         }
5498         bool used = false;
5499     };
5500 
5501     struct TestRunInfo {
5502         TestRunInfo( std::string const& _name );
5503         std::string name;
5504     };
5505     struct GroupInfo {
5506         GroupInfo(  std::string const& _name,
5507                     std::size_t _groupIndex,
5508                     std::size_t _groupsCount );
5509 
5510         std::string name;
5511         std::size_t groupIndex;
5512         std::size_t groupsCounts;
5513     };
5514 
5515     struct AssertionStats {
5516         AssertionStats( AssertionResult const& _assertionResult,
5517                         std::vector<MessageInfo> const& _infoMessages,
5518                         Totals const& _totals );
5519 
5520         AssertionStats( AssertionStats const& )              = default;
5521         AssertionStats( AssertionStats && )                  = default;
5522         AssertionStats& operator = ( AssertionStats const& ) = delete;
5523         AssertionStats& operator = ( AssertionStats && )     = delete;
5524         virtual ~AssertionStats();
5525 
5526         AssertionResult assertionResult;
5527         std::vector<MessageInfo> infoMessages;
5528         Totals totals;
5529     };
5530 
5531     struct SectionStats {
5532         SectionStats(   SectionInfo const& _sectionInfo,
5533                         Counts const& _assertions,
5534                         double _durationInSeconds,
5535                         bool _missingAssertions );
5536         SectionStats( SectionStats const& )              = default;
5537         SectionStats( SectionStats && )                  = default;
5538         SectionStats& operator = ( SectionStats const& ) = default;
5539         SectionStats& operator = ( SectionStats && )     = default;
5540         virtual ~SectionStats();
5541 
5542         SectionInfo sectionInfo;
5543         Counts assertions;
5544         double durationInSeconds;
5545         bool missingAssertions;
5546     };
5547 
5548     struct TestCaseStats {
5549         TestCaseStats(  TestCaseInfo const& _testInfo,
5550                         Totals const& _totals,
5551                         std::string const& _stdOut,
5552                         std::string const& _stdErr,
5553                         bool _aborting );
5554 
5555         TestCaseStats( TestCaseStats const& )              = default;
5556         TestCaseStats( TestCaseStats && )                  = default;
5557         TestCaseStats& operator = ( TestCaseStats const& ) = default;
5558         TestCaseStats& operator = ( TestCaseStats && )     = default;
5559         virtual ~TestCaseStats();
5560 
5561         TestCaseInfo testInfo;
5562         Totals totals;
5563         std::string stdOut;
5564         std::string stdErr;
5565         bool aborting;
5566     };
5567 
5568     struct TestGroupStats {
5569         TestGroupStats( GroupInfo const& _groupInfo,
5570                         Totals const& _totals,
5571                         bool _aborting );
5572         TestGroupStats( GroupInfo const& _groupInfo );
5573 
5574         TestGroupStats( TestGroupStats const& )              = default;
5575         TestGroupStats( TestGroupStats && )                  = default;
5576         TestGroupStats& operator = ( TestGroupStats const& ) = default;
5577         TestGroupStats& operator = ( TestGroupStats && )     = default;
5578         virtual ~TestGroupStats();
5579 
5580         GroupInfo groupInfo;
5581         Totals totals;
5582         bool aborting;
5583     };
5584 
5585     struct TestRunStats {
5586         TestRunStats(   TestRunInfo const& _runInfo,
5587                         Totals const& _totals,
5588                         bool _aborting );
5589 
5590         TestRunStats( TestRunStats const& )              = default;
5591         TestRunStats( TestRunStats && )                  = default;
5592         TestRunStats& operator = ( TestRunStats const& ) = default;
5593         TestRunStats& operator = ( TestRunStats && )     = default;
5594         virtual ~TestRunStats();
5595 
5596         TestRunInfo runInfo;
5597         Totals totals;
5598         bool aborting;
5599     };
5600 
5601 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5602     struct BenchmarkInfo {
5603         std::string name;
5604         double estimatedDuration;
5605         int iterations;
5606         int samples;
5607         unsigned int resamples;
5608         double clockResolution;
5609         double clockCost;
5610     };
5611 
5612     template <class Duration>
5613     struct BenchmarkStats {
5614         BenchmarkInfo info;
5615 
5616         std::vector<Duration> samples;
5617         Benchmark::Estimate<Duration> mean;
5618         Benchmark::Estimate<Duration> standardDeviation;
5619         Benchmark::OutlierClassification outliers;
5620         double outlierVariance;
5621 
5622         template <typename Duration2>
operator BenchmarkStats<Duration2>Catch::BenchmarkStats5623         operator BenchmarkStats<Duration2>() const {
5624             std::vector<Duration2> samples2;
5625             samples2.reserve(samples.size());
5626             std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5627             return {
5628                 info,
5629                 std::move(samples2),
5630                 mean,
5631                 standardDeviation,
5632                 outliers,
5633                 outlierVariance,
5634             };
5635         }
5636     };
5637 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5638 
5639     struct IStreamingReporter {
5640         virtual ~IStreamingReporter() = default;
5641 
5642         // Implementing class must also provide the following static methods:
5643         // static std::string getDescription();
5644         // static std::set<Verbosity> getSupportedVerbosities()
5645 
5646         virtual ReporterPreferences getPreferences() const = 0;
5647 
5648         virtual void noMatchingTestCases( std::string const& spec ) = 0;
5649 
reportInvalidArgumentsCatch::IStreamingReporter5650         virtual void reportInvalidArguments(std::string const&) {}
5651 
5652         virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5653         virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5654 
5655         virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5656         virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5657 
5658 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparingCatch::IStreamingReporter5659         virtual void benchmarkPreparing( std::string const& ) {}
benchmarkStartingCatch::IStreamingReporter5660         virtual void benchmarkStarting( BenchmarkInfo const& ) {}
benchmarkEndedCatch::IStreamingReporter5661         virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
benchmarkFailedCatch::IStreamingReporter5662         virtual void benchmarkFailed( std::string const& ) {}
5663 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5664 
5665         virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5666 
5667         // The return value indicates if the messages buffer should be cleared:
5668         virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5669 
5670         virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5671         virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5672         virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5673         virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5674 
5675         virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5676 
5677         // Default empty implementation provided
5678         virtual void fatalErrorEncountered( StringRef name );
5679 
5680         virtual bool isMulti() const;
5681     };
5682     using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5683 
5684     struct IReporterFactory {
5685         virtual ~IReporterFactory();
5686         virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5687         virtual std::string getDescription() const = 0;
5688     };
5689     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5690 
5691     struct IReporterRegistry {
5692         using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5693         using Listeners = std::vector<IReporterFactoryPtr>;
5694 
5695         virtual ~IReporterRegistry();
5696         virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5697         virtual FactoryMap const& getFactories() const = 0;
5698         virtual Listeners const& getListeners() const = 0;
5699     };
5700 
5701 } // end namespace Catch
5702 
5703 // end catch_interfaces_reporter.h
5704 #include <algorithm>
5705 #include <cstring>
5706 #include <cfloat>
5707 #include <cstdio>
5708 #include <cassert>
5709 #include <memory>
5710 #include <ostream>
5711 
5712 namespace Catch {
5713     void prepareExpandedExpression(AssertionResult& result);
5714 
5715     // Returns double formatted as %.3f (format expected on output)
5716     std::string getFormattedDuration( double duration );
5717 
5718     //! Should the reporter show
5719     bool shouldShowDuration( IConfig const& config, double duration );
5720 
5721     std::string serializeFilters( std::vector<std::string> const& container );
5722 
5723     template<typename DerivedT>
5724     struct StreamingReporterBase : IStreamingReporter {
5725 
StreamingReporterBaseCatch::StreamingReporterBase5726         StreamingReporterBase( ReporterConfig const& _config )
5727         :   m_config( _config.fullConfig() ),
5728             stream( _config.stream() )
5729         {
5730             m_reporterPrefs.shouldRedirectStdOut = false;
5731             if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5732                 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5733         }
5734 
getPreferencesCatch::StreamingReporterBase5735         ReporterPreferences getPreferences() const override {
5736             return m_reporterPrefs;
5737         }
5738 
getSupportedVerbositiesCatch::StreamingReporterBase5739         static std::set<Verbosity> getSupportedVerbosities() {
5740             return { Verbosity::Normal };
5741         }
5742 
5743         ~StreamingReporterBase() override = default;
5744 
noMatchingTestCasesCatch::StreamingReporterBase5745         void noMatchingTestCases(std::string const&) override {}
5746 
reportInvalidArgumentsCatch::StreamingReporterBase5747         void reportInvalidArguments(std::string const&) override {}
5748 
testRunStartingCatch::StreamingReporterBase5749         void testRunStarting(TestRunInfo const& _testRunInfo) override {
5750             currentTestRunInfo = _testRunInfo;
5751         }
5752 
testGroupStartingCatch::StreamingReporterBase5753         void testGroupStarting(GroupInfo const& _groupInfo) override {
5754             currentGroupInfo = _groupInfo;
5755         }
5756 
testCaseStartingCatch::StreamingReporterBase5757         void testCaseStarting(TestCaseInfo const& _testInfo) override  {
5758             currentTestCaseInfo = _testInfo;
5759         }
sectionStartingCatch::StreamingReporterBase5760         void sectionStarting(SectionInfo const& _sectionInfo) override {
5761             m_sectionStack.push_back(_sectionInfo);
5762         }
5763 
sectionEndedCatch::StreamingReporterBase5764         void sectionEnded(SectionStats const& /* _sectionStats */) override {
5765             m_sectionStack.pop_back();
5766         }
testCaseEndedCatch::StreamingReporterBase5767         void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5768             currentTestCaseInfo.reset();
5769         }
testGroupEndedCatch::StreamingReporterBase5770         void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5771             currentGroupInfo.reset();
5772         }
testRunEndedCatch::StreamingReporterBase5773         void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5774             currentTestCaseInfo.reset();
5775             currentGroupInfo.reset();
5776             currentTestRunInfo.reset();
5777         }
5778 
skipTestCatch::StreamingReporterBase5779         void skipTest(TestCaseInfo const&) override {
5780             // Don't do anything with this by default.
5781             // It can optionally be overridden in the derived class.
5782         }
5783 
5784         IConfigPtr m_config;
5785         std::ostream& stream;
5786 
5787         LazyStat<TestRunInfo> currentTestRunInfo;
5788         LazyStat<GroupInfo> currentGroupInfo;
5789         LazyStat<TestCaseInfo> currentTestCaseInfo;
5790 
5791         std::vector<SectionInfo> m_sectionStack;
5792         ReporterPreferences m_reporterPrefs;
5793     };
5794 
5795     template<typename DerivedT>
5796     struct CumulativeReporterBase : IStreamingReporter {
5797         template<typename T, typename ChildNodeT>
5798         struct Node {
NodeCatch::CumulativeReporterBase::Node5799             explicit Node( T const& _value ) : value( _value ) {}
~NodeCatch::CumulativeReporterBase::Node5800             virtual ~Node() {}
5801 
5802             using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5803             T value;
5804             ChildNodes children;
5805         };
5806         struct SectionNode {
SectionNodeCatch::CumulativeReporterBase::SectionNode5807             explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5808             virtual ~SectionNode() = default;
5809 
operator ==Catch::CumulativeReporterBase::SectionNode5810             bool operator == (SectionNode const& other) const {
5811                 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5812             }
operator ==Catch::CumulativeReporterBase::SectionNode5813             bool operator == (std::shared_ptr<SectionNode> const& other) const {
5814                 return operator==(*other);
5815             }
5816 
5817             SectionStats stats;
5818             using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5819             using Assertions = std::vector<AssertionStats>;
5820             ChildSections childSections;
5821             Assertions assertions;
5822             std::string stdOut;
5823             std::string stdErr;
5824         };
5825 
5826         struct BySectionInfo {
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5827             BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
BySectionInfoCatch::CumulativeReporterBase::BySectionInfo5828             BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
operator ()Catch::CumulativeReporterBase::BySectionInfo5829             bool operator() (std::shared_ptr<SectionNode> const& node) const {
5830                 return ((node->stats.sectionInfo.name == m_other.name) &&
5831                         (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5832             }
5833             void operator=(BySectionInfo const&) = delete;
5834 
5835         private:
5836             SectionInfo const& m_other;
5837         };
5838 
5839         using TestCaseNode = Node<TestCaseStats, SectionNode>;
5840         using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5841         using TestRunNode = Node<TestRunStats, TestGroupNode>;
5842 
CumulativeReporterBaseCatch::CumulativeReporterBase5843         CumulativeReporterBase( ReporterConfig const& _config )
5844         :   m_config( _config.fullConfig() ),
5845             stream( _config.stream() )
5846         {
5847             m_reporterPrefs.shouldRedirectStdOut = false;
5848             if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5849                 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5850         }
5851         ~CumulativeReporterBase() override = default;
5852 
getPreferencesCatch::CumulativeReporterBase5853         ReporterPreferences getPreferences() const override {
5854             return m_reporterPrefs;
5855         }
5856 
getSupportedVerbositiesCatch::CumulativeReporterBase5857         static std::set<Verbosity> getSupportedVerbosities() {
5858             return { Verbosity::Normal };
5859         }
5860 
testRunStartingCatch::CumulativeReporterBase5861         void testRunStarting( TestRunInfo const& ) override {}
testGroupStartingCatch::CumulativeReporterBase5862         void testGroupStarting( GroupInfo const& ) override {}
5863 
testCaseStartingCatch::CumulativeReporterBase5864         void testCaseStarting( TestCaseInfo const& ) override {}
5865 
sectionStartingCatch::CumulativeReporterBase5866         void sectionStarting( SectionInfo const& sectionInfo ) override {
5867             SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5868             std::shared_ptr<SectionNode> node;
5869             if( m_sectionStack.empty() ) {
5870                 if( !m_rootSection )
5871                     m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5872                 node = m_rootSection;
5873             }
5874             else {
5875                 SectionNode& parentNode = *m_sectionStack.back();
5876                 auto it =
5877                     std::find_if(   parentNode.childSections.begin(),
5878                                     parentNode.childSections.end(),
5879                                     BySectionInfo( sectionInfo ) );
5880                 if( it == parentNode.childSections.end() ) {
5881                     node = std::make_shared<SectionNode>( incompleteStats );
5882                     parentNode.childSections.push_back( node );
5883                 }
5884                 else
5885                     node = *it;
5886             }
5887             m_sectionStack.push_back( node );
5888             m_deepestSection = std::move(node);
5889         }
5890 
assertionStartingCatch::CumulativeReporterBase5891         void assertionStarting(AssertionInfo const&) override {}
5892 
assertionEndedCatch::CumulativeReporterBase5893         bool assertionEnded(AssertionStats const& assertionStats) override {
5894             assert(!m_sectionStack.empty());
5895             // AssertionResult holds a pointer to a temporary DecomposedExpression,
5896             // which getExpandedExpression() calls to build the expression string.
5897             // Our section stack copy of the assertionResult will likely outlive the
5898             // temporary, so it must be expanded or discarded now to avoid calling
5899             // a destroyed object later.
5900             prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5901             SectionNode& sectionNode = *m_sectionStack.back();
5902             sectionNode.assertions.push_back(assertionStats);
5903             return true;
5904         }
sectionEndedCatch::CumulativeReporterBase5905         void sectionEnded(SectionStats const& sectionStats) override {
5906             assert(!m_sectionStack.empty());
5907             SectionNode& node = *m_sectionStack.back();
5908             node.stats = sectionStats;
5909             m_sectionStack.pop_back();
5910         }
testCaseEndedCatch::CumulativeReporterBase5911         void testCaseEnded(TestCaseStats const& testCaseStats) override {
5912             auto node = std::make_shared<TestCaseNode>(testCaseStats);
5913             assert(m_sectionStack.size() == 0);
5914             node->children.push_back(m_rootSection);
5915             m_testCases.push_back(node);
5916             m_rootSection.reset();
5917 
5918             assert(m_deepestSection);
5919             m_deepestSection->stdOut = testCaseStats.stdOut;
5920             m_deepestSection->stdErr = testCaseStats.stdErr;
5921         }
testGroupEndedCatch::CumulativeReporterBase5922         void testGroupEnded(TestGroupStats const& testGroupStats) override {
5923             auto node = std::make_shared<TestGroupNode>(testGroupStats);
5924             node->children.swap(m_testCases);
5925             m_testGroups.push_back(node);
5926         }
testRunEndedCatch::CumulativeReporterBase5927         void testRunEnded(TestRunStats const& testRunStats) override {
5928             auto node = std::make_shared<TestRunNode>(testRunStats);
5929             node->children.swap(m_testGroups);
5930             m_testRuns.push_back(node);
5931             testRunEndedCumulative();
5932         }
5933         virtual void testRunEndedCumulative() = 0;
5934 
skipTestCatch::CumulativeReporterBase5935         void skipTest(TestCaseInfo const&) override {}
5936 
5937         IConfigPtr m_config;
5938         std::ostream& stream;
5939         std::vector<AssertionStats> m_assertions;
5940         std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5941         std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5942         std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5943 
5944         std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5945 
5946         std::shared_ptr<SectionNode> m_rootSection;
5947         std::shared_ptr<SectionNode> m_deepestSection;
5948         std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5949         ReporterPreferences m_reporterPrefs;
5950     };
5951 
5952     template<char C>
getLineOfChars()5953     char const* getLineOfChars() {
5954         static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5955         if( !*line ) {
5956             std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5957             line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5958         }
5959         return line;
5960     }
5961 
5962     struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5963         TestEventListenerBase( ReporterConfig const& _config );
5964 
5965         static std::set<Verbosity> getSupportedVerbosities();
5966 
5967         void assertionStarting(AssertionInfo const&) override;
5968         bool assertionEnded(AssertionStats const&) override;
5969     };
5970 
5971 } // end namespace Catch
5972 
5973 // end catch_reporter_bases.hpp
5974 // start catch_console_colour.h
5975 
5976 namespace Catch {
5977 
5978     struct Colour {
5979         enum Code {
5980             None = 0,
5981 
5982             White,
5983             Red,
5984             Green,
5985             Blue,
5986             Cyan,
5987             Yellow,
5988             Grey,
5989 
5990             Bright = 0x10,
5991 
5992             BrightRed = Bright | Red,
5993             BrightGreen = Bright | Green,
5994             LightGrey = Bright | Grey,
5995             BrightWhite = Bright | White,
5996             BrightYellow = Bright | Yellow,
5997 
5998             // By intention
5999             FileName = LightGrey,
6000             Warning = BrightYellow,
6001             ResultError = BrightRed,
6002             ResultSuccess = BrightGreen,
6003             ResultExpectedFailure = Warning,
6004 
6005             Error = BrightRed,
6006             Success = Green,
6007 
6008             OriginalExpression = Cyan,
6009             ReconstructedExpression = BrightYellow,
6010 
6011             SecondaryText = LightGrey,
6012             Headers = White
6013         };
6014 
6015         // Use constructed object for RAII guard
6016         Colour( Code _colourCode );
6017         Colour( Colour&& other ) noexcept;
6018         Colour& operator=( Colour&& other ) noexcept;
6019         ~Colour();
6020 
6021         // Use static method for one-shot changes
6022         static void use( Code _colourCode );
6023 
6024     private:
6025         bool m_moved = false;
6026     };
6027 
6028     std::ostream& operator << ( std::ostream& os, Colour const& );
6029 
6030 } // end namespace Catch
6031 
6032 // end catch_console_colour.h
6033 // start catch_reporter_registrars.hpp
6034 
6035 
6036 namespace Catch {
6037 
6038     template<typename T>
6039     class ReporterRegistrar {
6040 
6041         class ReporterFactory : public IReporterFactory {
6042 
create(ReporterConfig const & config) const6043             IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6044                 return std::unique_ptr<T>( new T( config ) );
6045             }
6046 
getDescription() const6047             std::string getDescription() const override {
6048                 return T::getDescription();
6049             }
6050         };
6051 
6052     public:
6053 
ReporterRegistrar(std::string const & name)6054         explicit ReporterRegistrar( std::string const& name ) {
6055             getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6056         }
6057     };
6058 
6059     template<typename T>
6060     class ListenerRegistrar {
6061 
6062         class ListenerFactory : public IReporterFactory {
6063 
create(ReporterConfig const & config) const6064             IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6065                 return std::unique_ptr<T>( new T( config ) );
6066             }
getDescription() const6067             std::string getDescription() const override {
6068                 return std::string();
6069             }
6070         };
6071 
6072     public:
6073 
ListenerRegistrar()6074         ListenerRegistrar() {
6075             getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6076         }
6077     };
6078 }
6079 
6080 #if !defined(CATCH_CONFIG_DISABLE)
6081 
6082 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6083     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION         \
6084     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS          \
6085     namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6086     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6087 
6088 #define CATCH_REGISTER_LISTENER( listenerType ) \
6089     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION   \
6090     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS    \
6091     namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6092     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6093 #else // CATCH_CONFIG_DISABLE
6094 
6095 #define CATCH_REGISTER_REPORTER(name, reporterType)
6096 #define CATCH_REGISTER_LISTENER(listenerType)
6097 
6098 #endif // CATCH_CONFIG_DISABLE
6099 
6100 // end catch_reporter_registrars.hpp
6101 // Allow users to base their work off existing reporters
6102 // start catch_reporter_compact.h
6103 
6104 namespace Catch {
6105 
6106     struct CompactReporter : StreamingReporterBase<CompactReporter> {
6107 
6108         using StreamingReporterBase::StreamingReporterBase;
6109 
6110         ~CompactReporter() override;
6111 
6112         static std::string getDescription();
6113 
6114         void noMatchingTestCases(std::string const& spec) override;
6115 
6116         void assertionStarting(AssertionInfo const&) override;
6117 
6118         bool assertionEnded(AssertionStats const& _assertionStats) override;
6119 
6120         void sectionEnded(SectionStats const& _sectionStats) override;
6121 
6122         void testRunEnded(TestRunStats const& _testRunStats) override;
6123 
6124     };
6125 
6126 } // end namespace Catch
6127 
6128 // end catch_reporter_compact.h
6129 // start catch_reporter_console.h
6130 
6131 #if defined(_MSC_VER)
6132 #pragma warning(push)
6133 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6134                               // Note that 4062 (not all labels are handled
6135                               // and default is missing) is enabled
6136 #endif
6137 
6138 namespace Catch {
6139     // Fwd decls
6140     struct SummaryColumn;
6141     class TablePrinter;
6142 
6143     struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6144         std::unique_ptr<TablePrinter> m_tablePrinter;
6145 
6146         ConsoleReporter(ReporterConfig const& config);
6147         ~ConsoleReporter() override;
6148         static std::string getDescription();
6149 
6150         void noMatchingTestCases(std::string const& spec) override;
6151 
6152         void reportInvalidArguments(std::string const&arg) override;
6153 
6154         void assertionStarting(AssertionInfo const&) override;
6155 
6156         bool assertionEnded(AssertionStats const& _assertionStats) override;
6157 
6158         void sectionStarting(SectionInfo const& _sectionInfo) override;
6159         void sectionEnded(SectionStats const& _sectionStats) override;
6160 
6161 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6162         void benchmarkPreparing(std::string const& name) override;
6163         void benchmarkStarting(BenchmarkInfo const& info) override;
6164         void benchmarkEnded(BenchmarkStats<> const& stats) override;
6165         void benchmarkFailed(std::string const& error) override;
6166 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6167 
6168         void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6169         void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6170         void testRunEnded(TestRunStats const& _testRunStats) override;
6171         void testRunStarting(TestRunInfo const& _testRunInfo) override;
6172     private:
6173 
6174         void lazyPrint();
6175 
6176         void lazyPrintWithoutClosingBenchmarkTable();
6177         void lazyPrintRunInfo();
6178         void lazyPrintGroupInfo();
6179         void printTestCaseAndSectionHeader();
6180 
6181         void printClosedHeader(std::string const& _name);
6182         void printOpenHeader(std::string const& _name);
6183 
6184         // if string has a : in first line will set indent to follow it on
6185         // subsequent lines
6186         void printHeaderString(std::string const& _string, std::size_t indent = 0);
6187 
6188         void printTotals(Totals const& totals);
6189         void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
6190 
6191         void printTotalsDivider(Totals const& totals);
6192         void printSummaryDivider();
6193         void printTestFilters();
6194 
6195     private:
6196         bool m_headerPrinted = false;
6197     };
6198 
6199 } // end namespace Catch
6200 
6201 #if defined(_MSC_VER)
6202 #pragma warning(pop)
6203 #endif
6204 
6205 // end catch_reporter_console.h
6206 // start catch_reporter_junit.h
6207 
6208 // start catch_xmlwriter.h
6209 
6210 #include <vector>
6211 
6212 namespace Catch {
6213     enum class XmlFormatting {
6214         None = 0x00,
6215         Indent = 0x01,
6216         Newline = 0x02,
6217     };
6218 
6219     XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6220     XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6221 
6222     class XmlEncode {
6223     public:
6224         enum ForWhat { ForTextNodes, ForAttributes };
6225 
6226         XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6227 
6228         void encodeTo( std::ostream& os ) const;
6229 
6230         friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6231 
6232     private:
6233         std::string m_str;
6234         ForWhat m_forWhat;
6235     };
6236 
6237     class XmlWriter {
6238     public:
6239 
6240         class ScopedElement {
6241         public:
6242             ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6243 
6244             ScopedElement( ScopedElement&& other ) noexcept;
6245             ScopedElement& operator=( ScopedElement&& other ) noexcept;
6246 
6247             ~ScopedElement();
6248 
6249             ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6250 
6251             template<typename T>
writeAttribute(std::string const & name,T const & attribute)6252             ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6253                 m_writer->writeAttribute( name, attribute );
6254                 return *this;
6255             }
6256 
6257         private:
6258             mutable XmlWriter* m_writer = nullptr;
6259             XmlFormatting m_fmt;
6260         };
6261 
6262         XmlWriter( std::ostream& os = Catch::cout() );
6263         ~XmlWriter();
6264 
6265         XmlWriter( XmlWriter const& ) = delete;
6266         XmlWriter& operator=( XmlWriter const& ) = delete;
6267 
6268         XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6269 
6270         ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6271 
6272         XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6273 
6274         XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6275 
6276         XmlWriter& writeAttribute( std::string const& name, bool attribute );
6277 
6278         template<typename T>
writeAttribute(std::string const & name,T const & attribute)6279         XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6280             ReusableStringStream rss;
6281             rss << attribute;
6282             return writeAttribute( name, rss.str() );
6283         }
6284 
6285         XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6286 
6287         XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6288 
6289         void writeStylesheetRef( std::string const& url );
6290 
6291         XmlWriter& writeBlankLine();
6292 
6293         void ensureTagClosed();
6294 
6295     private:
6296 
6297         void applyFormatting(XmlFormatting fmt);
6298 
6299         void writeDeclaration();
6300 
6301         void newlineIfNecessary();
6302 
6303         bool m_tagIsOpen = false;
6304         bool m_needsNewline = false;
6305         std::vector<std::string> m_tags;
6306         std::string m_indent;
6307         std::ostream& m_os;
6308     };
6309 
6310 }
6311 
6312 // end catch_xmlwriter.h
6313 namespace Catch {
6314 
6315     class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6316     public:
6317         JunitReporter(ReporterConfig const& _config);
6318 
6319         ~JunitReporter() override;
6320 
6321         static std::string getDescription();
6322 
6323         void noMatchingTestCases(std::string const& /*spec*/) override;
6324 
6325         void testRunStarting(TestRunInfo const& runInfo) override;
6326 
6327         void testGroupStarting(GroupInfo const& groupInfo) override;
6328 
6329         void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6330         bool assertionEnded(AssertionStats const& assertionStats) override;
6331 
6332         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6333 
6334         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6335 
6336         void testRunEndedCumulative() override;
6337 
6338         void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6339 
6340         void writeTestCase(TestCaseNode const& testCaseNode);
6341 
6342         void writeSection(std::string const& className,
6343                           std::string const& rootName,
6344                           SectionNode const& sectionNode);
6345 
6346         void writeAssertions(SectionNode const& sectionNode);
6347         void writeAssertion(AssertionStats const& stats);
6348 
6349         XmlWriter xml;
6350         Timer suiteTimer;
6351         std::string stdOutForSuite;
6352         std::string stdErrForSuite;
6353         unsigned int unexpectedExceptions = 0;
6354         bool m_okToFail = false;
6355     };
6356 
6357 } // end namespace Catch
6358 
6359 // end catch_reporter_junit.h
6360 // start catch_reporter_xml.h
6361 
6362 namespace Catch {
6363     class XmlReporter : public StreamingReporterBase<XmlReporter> {
6364     public:
6365         XmlReporter(ReporterConfig const& _config);
6366 
6367         ~XmlReporter() override;
6368 
6369         static std::string getDescription();
6370 
6371         virtual std::string getStylesheetRef() const;
6372 
6373         void writeSourceInfo(SourceLineInfo const& sourceInfo);
6374 
6375     public: // StreamingReporterBase
6376 
6377         void noMatchingTestCases(std::string const& s) override;
6378 
6379         void testRunStarting(TestRunInfo const& testInfo) override;
6380 
6381         void testGroupStarting(GroupInfo const& groupInfo) override;
6382 
6383         void testCaseStarting(TestCaseInfo const& testInfo) override;
6384 
6385         void sectionStarting(SectionInfo const& sectionInfo) override;
6386 
6387         void assertionStarting(AssertionInfo const&) override;
6388 
6389         bool assertionEnded(AssertionStats const& assertionStats) override;
6390 
6391         void sectionEnded(SectionStats const& sectionStats) override;
6392 
6393         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6394 
6395         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6396 
6397         void testRunEnded(TestRunStats const& testRunStats) override;
6398 
6399 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6400         void benchmarkPreparing(std::string const& name) override;
6401         void benchmarkStarting(BenchmarkInfo const&) override;
6402         void benchmarkEnded(BenchmarkStats<> const&) override;
6403         void benchmarkFailed(std::string const&) override;
6404 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6405 
6406     private:
6407         Timer m_testCaseTimer;
6408         XmlWriter m_xml;
6409         int m_sectionDepth = 0;
6410     };
6411 
6412 } // end namespace Catch
6413 
6414 // end catch_reporter_xml.h
6415 
6416 // end catch_external_interfaces.h
6417 #endif
6418 
6419 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6420 // start catch_benchmarking_all.hpp
6421 
6422 // A proxy header that includes all of the benchmarking headers to allow
6423 // concise include of the benchmarking features. You should prefer the
6424 // individual includes in standard use.
6425 
6426 // start catch_benchmark.hpp
6427 
6428  // Benchmark
6429 
6430 // start catch_chronometer.hpp
6431 
6432 // User-facing chronometer
6433 
6434 
6435 // start catch_clock.hpp
6436 
6437 // Clocks
6438 
6439 
6440 #include <chrono>
6441 #include <ratio>
6442 
6443 namespace Catch {
6444     namespace Benchmark {
6445         template <typename Clock>
6446         using ClockDuration = typename Clock::duration;
6447         template <typename Clock>
6448         using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6449 
6450         template <typename Clock>
6451         using TimePoint = typename Clock::time_point;
6452 
6453         using default_clock = std::chrono::steady_clock;
6454 
6455         template <typename Clock>
6456         struct now {
operator ()Catch::Benchmark::now6457             TimePoint<Clock> operator()() const {
6458                 return Clock::now();
6459             }
6460         };
6461 
6462         using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6463     } // namespace Benchmark
6464 } // namespace Catch
6465 
6466 // end catch_clock.hpp
6467 // start catch_optimizer.hpp
6468 
6469  // Hinting the optimizer
6470 
6471 
6472 #if defined(_MSC_VER)
6473 #   include <atomic> // atomic_thread_fence
6474 #endif
6475 
6476 namespace Catch {
6477     namespace Benchmark {
6478 #if defined(__GNUC__) || defined(__clang__)
6479         template <typename T>
keep_memory(T * p)6480         inline void keep_memory(T* p) {
6481             asm volatile("" : : "g"(p) : "memory");
6482         }
keep_memory()6483         inline void keep_memory() {
6484             asm volatile("" : : : "memory");
6485         }
6486 
6487         namespace Detail {
optimizer_barrier()6488             inline void optimizer_barrier() { keep_memory(); }
6489         } // namespace Detail
6490 #elif defined(_MSC_VER)
6491 
6492 #pragma optimize("", off)
6493         template <typename T>
6494         inline void keep_memory(T* p) {
6495             // thanks @milleniumbug
6496             *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6497         }
6498         // TODO equivalent keep_memory()
6499 #pragma optimize("", on)
6500 
6501         namespace Detail {
6502             inline void optimizer_barrier() {
6503                 std::atomic_thread_fence(std::memory_order_seq_cst);
6504             }
6505         } // namespace Detail
6506 
6507 #endif
6508 
6509         template <typename T>
deoptimize_value(T && x)6510         inline void deoptimize_value(T&& x) {
6511             keep_memory(&x);
6512         }
6513 
6514         template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6515         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6516             deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6517         }
6518 
6519         template <typename Fn, typename... Args>
invoke_deoptimized(Fn && fn,Args &&...args)6520         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6521             std::forward<Fn>(fn) (std::forward<Args...>(args...));
6522         }
6523     } // namespace Benchmark
6524 } // namespace Catch
6525 
6526 // end catch_optimizer.hpp
6527 // start catch_complete_invoke.hpp
6528 
6529 // Invoke with a special case for void
6530 
6531 
6532 #include <type_traits>
6533 #include <utility>
6534 
6535 namespace Catch {
6536     namespace Benchmark {
6537         namespace Detail {
6538             template <typename T>
6539             struct CompleteType { using type = T; };
6540             template <>
6541             struct CompleteType<void> { struct type {}; };
6542 
6543             template <typename T>
6544             using CompleteType_t = typename CompleteType<T>::type;
6545 
6546             template <typename Result>
6547             struct CompleteInvoker {
6548                 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6549                 static Result invoke(Fun&& fun, Args&&... args) {
6550                     return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6551                 }
6552             };
6553             template <>
6554             struct CompleteInvoker<void> {
6555                 template <typename Fun, typename... Args>
invokeCatch::Benchmark::Detail::CompleteInvoker6556                 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6557                     std::forward<Fun>(fun)(std::forward<Args>(args)...);
6558                     return {};
6559                 }
6560             };
6561 
6562             // invoke and not return void :(
6563             template <typename Fun, typename... Args>
complete_invoke(Fun && fun,Args &&...args)6564             CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6565                 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6566             }
6567 
6568             const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6569         } // namespace Detail
6570 
6571         template <typename Fun>
user_code(Fun && fun)6572         Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6573             CATCH_TRY{
6574                 return Detail::complete_invoke(std::forward<Fun>(fun));
6575             } CATCH_CATCH_ALL{
6576                 getResultCapture().benchmarkFailed(translateActiveException());
6577                 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6578             }
6579         }
6580     } // namespace Benchmark
6581 } // namespace Catch
6582 
6583 // end catch_complete_invoke.hpp
6584 namespace Catch {
6585     namespace Benchmark {
6586         namespace Detail {
6587             struct ChronometerConcept {
6588                 virtual void start() = 0;
6589                 virtual void finish() = 0;
6590                 virtual ~ChronometerConcept() = default;
6591             };
6592             template <typename Clock>
6593             struct ChronometerModel final : public ChronometerConcept {
startCatch::Benchmark::Detail::ChronometerModel6594                 void start() override { started = Clock::now(); }
finishCatch::Benchmark::Detail::ChronometerModel6595                 void finish() override { finished = Clock::now(); }
6596 
elapsedCatch::Benchmark::Detail::ChronometerModel6597                 ClockDuration<Clock> elapsed() const { return finished - started; }
6598 
6599                 TimePoint<Clock> started;
6600                 TimePoint<Clock> finished;
6601             };
6602         } // namespace Detail
6603 
6604         struct Chronometer {
6605         public:
6606             template <typename Fun>
measureCatch::Benchmark::Chronometer6607             void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6608 
runsCatch::Benchmark::Chronometer6609             int runs() const { return k; }
6610 
ChronometerCatch::Benchmark::Chronometer6611             Chronometer(Detail::ChronometerConcept& meter, int k)
6612                 : impl(&meter)
6613                 , k(k) {}
6614 
6615         private:
6616             template <typename Fun>
measureCatch::Benchmark::Chronometer6617             void measure(Fun&& fun, std::false_type) {
6618                 measure([&fun](int) { return fun(); }, std::true_type());
6619             }
6620 
6621             template <typename Fun>
measureCatch::Benchmark::Chronometer6622             void measure(Fun&& fun, std::true_type) {
6623                 Detail::optimizer_barrier();
6624                 impl->start();
6625                 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6626                 impl->finish();
6627                 Detail::optimizer_barrier();
6628             }
6629 
6630             Detail::ChronometerConcept* impl;
6631             int k;
6632         };
6633     } // namespace Benchmark
6634 } // namespace Catch
6635 
6636 // end catch_chronometer.hpp
6637 // start catch_environment.hpp
6638 
6639 // Environment information
6640 
6641 
6642 namespace Catch {
6643     namespace Benchmark {
6644         template <typename Duration>
6645         struct EnvironmentEstimate {
6646             Duration mean;
6647             OutlierClassification outliers;
6648 
6649             template <typename Duration2>
operator EnvironmentEstimate<Duration2>Catch::Benchmark::EnvironmentEstimate6650             operator EnvironmentEstimate<Duration2>() const {
6651                 return { mean, outliers };
6652             }
6653         };
6654         template <typename Clock>
6655         struct Environment {
6656             using clock_type = Clock;
6657             EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6658             EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6659         };
6660     } // namespace Benchmark
6661 } // namespace Catch
6662 
6663 // end catch_environment.hpp
6664 // start catch_execution_plan.hpp
6665 
6666  // Execution plan
6667 
6668 
6669 // start catch_benchmark_function.hpp
6670 
6671  // Dumb std::function implementation for consistent call overhead
6672 
6673 
6674 #include <cassert>
6675 #include <type_traits>
6676 #include <utility>
6677 #include <memory>
6678 
6679 namespace Catch {
6680     namespace Benchmark {
6681         namespace Detail {
6682             template <typename T>
6683             using Decay = typename std::decay<T>::type;
6684             template <typename T, typename U>
6685             struct is_related
6686                 : std::is_same<Decay<T>, Decay<U>> {};
6687 
6688             /// We need to reinvent std::function because every piece of code that might add overhead
6689             /// in a measurement context needs to have consistent performance characteristics so that we
6690             /// can account for it in the measurement.
6691             /// Implementations of std::function with optimizations that aren't always applicable, like
6692             /// small buffer optimizations, are not uncommon.
6693             /// This is effectively an implementation of std::function without any such optimizations;
6694             /// it may be slow, but it is consistently slow.
6695             struct BenchmarkFunction {
6696             private:
6697                 struct callable {
6698                     virtual void call(Chronometer meter) const = 0;
6699                     virtual callable* clone() const = 0;
6700                     virtual ~callable() = default;
6701                 };
6702                 template <typename Fun>
6703                 struct model : public callable {
modelCatch::Benchmark::Detail::BenchmarkFunction::model6704                     model(Fun&& fun) : fun(std::move(fun)) {}
modelCatch::Benchmark::Detail::BenchmarkFunction::model6705                     model(Fun const& fun) : fun(fun) {}
6706 
cloneCatch::Benchmark::Detail::BenchmarkFunction::model6707                     model<Fun>* clone() const override { return new model<Fun>(*this); }
6708 
callCatch::Benchmark::Detail::BenchmarkFunction::model6709                     void call(Chronometer meter) const override {
6710                         call(meter, is_callable<Fun(Chronometer)>());
6711                     }
callCatch::Benchmark::Detail::BenchmarkFunction::model6712                     void call(Chronometer meter, std::true_type) const {
6713                         fun(meter);
6714                     }
callCatch::Benchmark::Detail::BenchmarkFunction::model6715                     void call(Chronometer meter, std::false_type) const {
6716                         meter.measure(fun);
6717                     }
6718 
6719                     Fun fun;
6720                 };
6721 
operator ()Catch::Benchmark::Detail::BenchmarkFunction::do_nothing6722                 struct do_nothing { void operator()() const {} };
6723 
6724                 template <typename T>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6725                 BenchmarkFunction(model<T>* c) : f(c) {}
6726 
6727             public:
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6728                 BenchmarkFunction()
6729                     : f(new model<do_nothing>{ {} }) {}
6730 
6731                 template <typename Fun,
6732                     typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6733                     BenchmarkFunction(Fun&& fun)
6734                     : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6735 
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6736                 BenchmarkFunction(BenchmarkFunction&& that)
6737                     : f(std::move(that.f)) {}
6738 
BenchmarkFunctionCatch::Benchmark::Detail::BenchmarkFunction6739                 BenchmarkFunction(BenchmarkFunction const& that)
6740                     : f(that.f->clone()) {}
6741 
operator =Catch::Benchmark::Detail::BenchmarkFunction6742                 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6743                     f = std::move(that.f);
6744                     return *this;
6745                 }
6746 
operator =Catch::Benchmark::Detail::BenchmarkFunction6747                 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6748                     f.reset(that.f->clone());
6749                     return *this;
6750                 }
6751 
operator ()Catch::Benchmark::Detail::BenchmarkFunction6752                 void operator()(Chronometer meter) const { f->call(meter); }
6753 
6754             private:
6755                 std::unique_ptr<callable> f;
6756             };
6757         } // namespace Detail
6758     } // namespace Benchmark
6759 } // namespace Catch
6760 
6761 // end catch_benchmark_function.hpp
6762 // start catch_repeat.hpp
6763 
6764 // repeat algorithm
6765 
6766 
6767 #include <type_traits>
6768 #include <utility>
6769 
6770 namespace Catch {
6771     namespace Benchmark {
6772         namespace Detail {
6773             template <typename Fun>
6774             struct repeater {
operator ()Catch::Benchmark::Detail::repeater6775                 void operator()(int k) const {
6776                     for (int i = 0; i < k; ++i) {
6777                         fun();
6778                     }
6779                 }
6780                 Fun fun;
6781             };
6782             template <typename Fun>
repeat(Fun && fun)6783             repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6784                 return { std::forward<Fun>(fun) };
6785             }
6786         } // namespace Detail
6787     } // namespace Benchmark
6788 } // namespace Catch
6789 
6790 // end catch_repeat.hpp
6791 // start catch_run_for_at_least.hpp
6792 
6793 // Run a function for a minimum amount of time
6794 
6795 
6796 // start catch_measure.hpp
6797 
6798 // Measure
6799 
6800 
6801 // start catch_timing.hpp
6802 
6803 // Timing
6804 
6805 
6806 #include <tuple>
6807 #include <type_traits>
6808 
6809 namespace Catch {
6810     namespace Benchmark {
6811         template <typename Duration, typename Result>
6812         struct Timing {
6813             Duration elapsed;
6814             Result result;
6815             int iterations;
6816         };
6817         template <typename Clock, typename Func, typename... Args>
6818         using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6819     } // namespace Benchmark
6820 } // namespace Catch
6821 
6822 // end catch_timing.hpp
6823 #include <utility>
6824 
6825 namespace Catch {
6826     namespace Benchmark {
6827         namespace Detail {
6828             template <typename Clock, typename Fun, typename... Args>
measure(Fun && fun,Args &&...args)6829             TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6830                 auto start = Clock::now();
6831                 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6832                 auto end = Clock::now();
6833                 auto delta = end - start;
6834                 return { delta, std::forward<decltype(r)>(r), 1 };
6835             }
6836         } // namespace Detail
6837     } // namespace Benchmark
6838 } // namespace Catch
6839 
6840 // end catch_measure.hpp
6841 #include <utility>
6842 #include <type_traits>
6843 
6844 namespace Catch {
6845     namespace Benchmark {
6846         namespace Detail {
6847             template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::false_type)6848             TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6849                 return Detail::measure<Clock>(fun, iters);
6850             }
6851             template <typename Clock, typename Fun>
measure_one(Fun && fun,int iters,std::true_type)6852             TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6853                 Detail::ChronometerModel<Clock> meter;
6854                 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6855 
6856                 return { meter.elapsed(), std::move(result), iters };
6857             }
6858 
6859             template <typename Clock, typename Fun>
6860             using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6861 
6862             struct optimized_away_error : std::exception {
whatCatch::Benchmark::Detail::optimized_away_error6863                 const char* what() const noexcept override {
6864                     return "could not measure benchmark, maybe it was optimized away";
6865                 }
6866             };
6867 
6868             template <typename Clock, typename Fun>
run_for_at_least(ClockDuration<Clock> how_long,int seed,Fun && fun)6869             TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6870                 auto iters = seed;
6871                 while (iters < (1 << 30)) {
6872                     auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6873 
6874                     if (Timing.elapsed >= how_long) {
6875                         return { Timing.elapsed, std::move(Timing.result), iters };
6876                     }
6877                     iters *= 2;
6878                 }
6879                 throw optimized_away_error{};
6880             }
6881         } // namespace Detail
6882     } // namespace Benchmark
6883 } // namespace Catch
6884 
6885 // end catch_run_for_at_least.hpp
6886 #include <algorithm>
6887 
6888 namespace Catch {
6889     namespace Benchmark {
6890         template <typename Duration>
6891         struct ExecutionPlan {
6892             int iterations_per_sample;
6893             Duration estimated_duration;
6894             Detail::BenchmarkFunction benchmark;
6895             Duration warmup_time;
6896             int warmup_iterations;
6897 
6898             template <typename Duration2>
operator ExecutionPlan<Duration2>Catch::Benchmark::ExecutionPlan6899             operator ExecutionPlan<Duration2>() const {
6900                 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6901             }
6902 
6903             template <typename Clock>
runCatch::Benchmark::ExecutionPlan6904             std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6905                 // warmup a bit
6906                 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6907 
6908                 std::vector<FloatDuration<Clock>> times;
6909                 times.reserve(cfg.benchmarkSamples());
6910                 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6911                     Detail::ChronometerModel<Clock> model;
6912                     this->benchmark(Chronometer(model, iterations_per_sample));
6913                     auto sample_time = model.elapsed() - env.clock_cost.mean;
6914                     if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6915                     return sample_time / iterations_per_sample;
6916                 });
6917                 return times;
6918             }
6919         };
6920     } // namespace Benchmark
6921 } // namespace Catch
6922 
6923 // end catch_execution_plan.hpp
6924 // start catch_estimate_clock.hpp
6925 
6926  // Environment measurement
6927 
6928 
6929 // start catch_stats.hpp
6930 
6931 // Statistical analysis tools
6932 
6933 
6934 #include <algorithm>
6935 #include <functional>
6936 #include <vector>
6937 #include <iterator>
6938 #include <numeric>
6939 #include <tuple>
6940 #include <cmath>
6941 #include <utility>
6942 #include <cstddef>
6943 #include <random>
6944 
6945 namespace Catch {
6946     namespace Benchmark {
6947         namespace Detail {
6948             using sample = std::vector<double>;
6949 
6950             double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6951 
6952             template <typename Iterator>
classify_outliers(Iterator first,Iterator last)6953             OutlierClassification classify_outliers(Iterator first, Iterator last) {
6954                 std::vector<double> copy(first, last);
6955 
6956                 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6957                 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6958                 auto iqr = q3 - q1;
6959                 auto los = q1 - (iqr * 3.);
6960                 auto lom = q1 - (iqr * 1.5);
6961                 auto him = q3 + (iqr * 1.5);
6962                 auto his = q3 + (iqr * 3.);
6963 
6964                 OutlierClassification o;
6965                 for (; first != last; ++first) {
6966                     auto&& t = *first;
6967                     if (t < los) ++o.low_severe;
6968                     else if (t < lom) ++o.low_mild;
6969                     else if (t > his) ++o.high_severe;
6970                     else if (t > him) ++o.high_mild;
6971                     ++o.samples_seen;
6972                 }
6973                 return o;
6974             }
6975 
6976             template <typename Iterator>
mean(Iterator first,Iterator last)6977             double mean(Iterator first, Iterator last) {
6978                 auto count = last - first;
6979                 double sum = std::accumulate(first, last, 0.);
6980                 return sum / count;
6981             }
6982 
6983             template <typename URng, typename Iterator, typename Estimator>
resample(URng & rng,int resamples,Iterator first,Iterator last,Estimator & estimator)6984             sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
6985                 auto n = last - first;
6986                 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6987 
6988                 sample out;
6989                 out.reserve(resamples);
6990                 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6991                     std::vector<double> resampled;
6992                     resampled.reserve(n);
6993                     std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
6994                     return estimator(resampled.begin(), resampled.end());
6995                 });
6996                 std::sort(out.begin(), out.end());
6997                 return out;
6998             }
6999 
7000             template <typename Estimator, typename Iterator>
jackknife(Estimator && estimator,Iterator first,Iterator last)7001             sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7002                 auto n = last - first;
7003                 auto second = std::next(first);
7004                 sample results;
7005                 results.reserve(n);
7006 
7007                 for (auto it = first; it != last; ++it) {
7008                     std::iter_swap(it, first);
7009                     results.push_back(estimator(second, last));
7010                 }
7011 
7012                 return results;
7013             }
7014 
normal_cdf(double x)7015             inline double normal_cdf(double x) {
7016                 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7017             }
7018 
7019             double erfc_inv(double x);
7020 
7021             double normal_quantile(double p);
7022 
7023             template <typename Iterator, typename Estimator>
bootstrap(double confidence_level,Iterator first,Iterator last,sample const & resample,Estimator && estimator)7024             Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
7025                 auto n_samples = last - first;
7026 
7027                 double point = estimator(first, last);
7028                 // Degenerate case with a single sample
7029                 if (n_samples == 1) return { point, point, point, confidence_level };
7030 
7031                 sample jack = jackknife(estimator, first, last);
7032                 double jack_mean = mean(jack.begin(), jack.end());
7033                 double sum_squares, sum_cubes;
7034                 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> {
7035                     auto d = jack_mean - x;
7036                     auto d2 = d * d;
7037                     auto d3 = d2 * d;
7038                     return { sqcb.first + d2, sqcb.second + d3 };
7039                 });
7040 
7041                 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7042                 int n = static_cast<int>(resample.size());
7043                 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
7044                 // degenerate case with uniform samples
7045                 if (prob_n == 0) return { point, point, point, confidence_level };
7046 
7047                 double bias = normal_quantile(prob_n);
7048                 double z1 = normal_quantile((1. - confidence_level) / 2.);
7049 
7050                 auto cumn = [n](double x) -> int {
7051                     return std::lround(normal_cdf(x) * n); };
7052                 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7053                 double b1 = bias + z1;
7054                 double b2 = bias - z1;
7055                 double a1 = a(b1);
7056                 double a2 = a(b2);
7057                 auto lo = std::max(cumn(a1), 0);
7058                 auto hi = std::min(cumn(a2), n - 1);
7059 
7060                 return { point, resample[lo], resample[hi], confidence_level };
7061             }
7062 
7063             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7064 
7065             struct bootstrap_analysis {
7066                 Estimate<double> mean;
7067                 Estimate<double> standard_deviation;
7068                 double outlier_variance;
7069             };
7070 
7071             bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7072         } // namespace Detail
7073     } // namespace Benchmark
7074 } // namespace Catch
7075 
7076 // end catch_stats.hpp
7077 #include <algorithm>
7078 #include <iterator>
7079 #include <tuple>
7080 #include <vector>
7081 #include <cmath>
7082 
7083 namespace Catch {
7084     namespace Benchmark {
7085         namespace Detail {
7086             template <typename Clock>
resolution(int k)7087             std::vector<double> resolution(int k) {
7088                 std::vector<TimePoint<Clock>> times;
7089                 times.reserve(k + 1);
7090                 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7091 
7092                 std::vector<double> deltas;
7093                 deltas.reserve(k);
7094                 std::transform(std::next(times.begin()), times.end(), times.begin(),
7095                     std::back_inserter(deltas),
7096                     [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7097 
7098                 return deltas;
7099             }
7100 
7101             const auto warmup_iterations = 10000;
7102             const auto warmup_time = std::chrono::milliseconds(100);
7103             const auto minimum_ticks = 1000;
7104             const auto warmup_seed = 10000;
7105             const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7106             const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7107             const auto clock_cost_estimation_tick_limit = 100000;
7108             const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7109             const auto clock_cost_estimation_iterations = 10000;
7110 
7111             template <typename Clock>
warmup()7112             int warmup() {
7113                 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7114                     .iterations;
7115             }
7116             template <typename Clock>
estimate_clock_resolution(int iterations)7117             EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7118                 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7119                     .result;
7120                 return {
7121                     FloatDuration<Clock>(mean(r.begin(), r.end())),
7122                     classify_outliers(r.begin(), r.end()),
7123                 };
7124             }
7125             template <typename Clock>
estimate_clock_cost(FloatDuration<Clock> resolution)7126             EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7127                 auto time_limit = std::min(resolution * clock_cost_estimation_tick_limit, FloatDuration<Clock>(clock_cost_estimation_time_limit));
7128                 auto time_clock = [](int k) {
7129                     return Detail::measure<Clock>([k] {
7130                         for (int i = 0; i < k; ++i) {
7131                             volatile auto ignored = Clock::now();
7132                             (void)ignored;
7133                         }
7134                     }).elapsed;
7135                 };
7136                 time_clock(1);
7137                 int iters = clock_cost_estimation_iterations;
7138                 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7139                 std::vector<double> times;
7140                 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7141                 times.reserve(nsamples);
7142                 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7143                     return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7144                 });
7145                 return {
7146                     FloatDuration<Clock>(mean(times.begin(), times.end())),
7147                     classify_outliers(times.begin(), times.end()),
7148                 };
7149             }
7150 
7151             template <typename Clock>
measure_environment()7152             Environment<FloatDuration<Clock>> measure_environment() {
7153                 static Environment<FloatDuration<Clock>>* env = nullptr;
7154                 if (env) {
7155                     return *env;
7156                 }
7157 
7158                 auto iters = Detail::warmup<Clock>();
7159                 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7160                 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7161 
7162                 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
7163                 return *env;
7164             }
7165         } // namespace Detail
7166     } // namespace Benchmark
7167 } // namespace Catch
7168 
7169 // end catch_estimate_clock.hpp
7170 // start catch_analyse.hpp
7171 
7172  // Run and analyse one benchmark
7173 
7174 
7175 // start catch_sample_analysis.hpp
7176 
7177 // Benchmark results
7178 
7179 
7180 #include <algorithm>
7181 #include <vector>
7182 #include <string>
7183 #include <iterator>
7184 
7185 namespace Catch {
7186     namespace Benchmark {
7187         template <typename Duration>
7188         struct SampleAnalysis {
7189             std::vector<Duration> samples;
7190             Estimate<Duration> mean;
7191             Estimate<Duration> standard_deviation;
7192             OutlierClassification outliers;
7193             double outlier_variance;
7194 
7195             template <typename Duration2>
operator SampleAnalysis<Duration2>Catch::Benchmark::SampleAnalysis7196             operator SampleAnalysis<Duration2>() const {
7197                 std::vector<Duration2> samples2;
7198                 samples2.reserve(samples.size());
7199                 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7200                 return {
7201                     std::move(samples2),
7202                     mean,
7203                     standard_deviation,
7204                     outliers,
7205                     outlier_variance,
7206                 };
7207             }
7208         };
7209     } // namespace Benchmark
7210 } // namespace Catch
7211 
7212 // end catch_sample_analysis.hpp
7213 #include <algorithm>
7214 #include <iterator>
7215 #include <vector>
7216 
7217 namespace Catch {
7218     namespace Benchmark {
7219         namespace Detail {
7220             template <typename Duration, typename Iterator>
analyse(const IConfig & cfg,Environment<Duration>,Iterator first,Iterator last)7221             SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7222                 if (!cfg.benchmarkNoAnalysis()) {
7223                     std::vector<double> samples;
7224                     samples.reserve(last - first);
7225                     std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7226 
7227                     auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7228                     auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7229 
7230                     auto wrap_estimate = [](Estimate<double> e) {
7231                         return Estimate<Duration> {
7232                             Duration(e.point),
7233                                 Duration(e.lower_bound),
7234                                 Duration(e.upper_bound),
7235                                 e.confidence_interval,
7236                         };
7237                     };
7238                     std::vector<Duration> samples2;
7239                     samples2.reserve(samples.size());
7240                     std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7241                     return {
7242                         std::move(samples2),
7243                         wrap_estimate(analysis.mean),
7244                         wrap_estimate(analysis.standard_deviation),
7245                         outliers,
7246                         analysis.outlier_variance,
7247                     };
7248                 } else {
7249                     std::vector<Duration> samples;
7250                     samples.reserve(last - first);
7251 
7252                     Duration mean = Duration(0);
7253                     int i = 0;
7254                     for (auto it = first; it < last; ++it, ++i) {
7255                         samples.push_back(Duration(*it));
7256                         mean += Duration(*it);
7257                     }
7258                     mean /= i;
7259 
7260                     return {
7261                         std::move(samples),
7262                         Estimate<Duration>{mean, mean, mean, 0.0},
7263                         Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7264                         OutlierClassification{},
7265                         0.0
7266                     };
7267                 }
7268             }
7269         } // namespace Detail
7270     } // namespace Benchmark
7271 } // namespace Catch
7272 
7273 // end catch_analyse.hpp
7274 #include <algorithm>
7275 #include <functional>
7276 #include <string>
7277 #include <vector>
7278 #include <cmath>
7279 
7280 namespace Catch {
7281     namespace Benchmark {
7282         struct Benchmark {
BenchmarkCatch::Benchmark::Benchmark7283             Benchmark(std::string &&name)
7284                 : name(std::move(name)) {}
7285 
7286             template <class FUN>
BenchmarkCatch::Benchmark::Benchmark7287             Benchmark(std::string &&name, FUN &&func)
7288                 : fun(std::move(func)), name(std::move(name)) {}
7289 
7290             template <typename Clock>
prepareCatch::Benchmark::Benchmark7291             ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7292                 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7293                 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7294                 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7295                 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7296                 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7297             }
7298 
7299             template <typename Clock = default_clock>
runCatch::Benchmark::Benchmark7300             void run() {
7301                 IConfigPtr cfg = getCurrentContext().getConfig();
7302 
7303                 auto env = Detail::measure_environment<Clock>();
7304 
7305                 getResultCapture().benchmarkPreparing(name);
7306                 CATCH_TRY{
7307                     auto plan = user_code([&] {
7308                         return prepare<Clock>(*cfg, env);
7309                     });
7310 
7311                     BenchmarkInfo info {
7312                         name,
7313                         plan.estimated_duration.count(),
7314                         plan.iterations_per_sample,
7315                         cfg->benchmarkSamples(),
7316                         cfg->benchmarkResamples(),
7317                         env.clock_resolution.mean.count(),
7318                         env.clock_cost.mean.count()
7319                     };
7320 
7321                     getResultCapture().benchmarkStarting(info);
7322 
7323                     auto samples = user_code([&] {
7324                         return plan.template run<Clock>(*cfg, env);
7325                     });
7326 
7327                     auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7328                     BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7329                     getResultCapture().benchmarkEnded(stats);
7330 
7331                 } CATCH_CATCH_ALL{
7332                     if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7333                         std::rethrow_exception(std::current_exception());
7334                 }
7335             }
7336 
7337             // sets lambda to be used in fun *and* executes benchmark!
7338             template <typename Fun,
7339                 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
operator =Catch::Benchmark::Benchmark7340                 Benchmark & operator=(Fun func) {
7341                 fun = Detail::BenchmarkFunction(func);
7342                 run();
7343                 return *this;
7344             }
7345 
operator boolCatch::Benchmark::Benchmark7346             explicit operator bool() {
7347                 return true;
7348             }
7349 
7350         private:
7351             Detail::BenchmarkFunction fun;
7352             std::string name;
7353         };
7354     }
7355 } // namespace Catch
7356 
7357 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7358 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7359 
7360 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7361     if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7362         BenchmarkName = [&](int benchmarkIndex)
7363 
7364 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7365     if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7366         BenchmarkName = [&]
7367 
7368 // end catch_benchmark.hpp
7369 // start catch_constructor.hpp
7370 
7371 // Constructor and destructor helpers
7372 
7373 
7374 #include <type_traits>
7375 
7376 namespace Catch {
7377     namespace Benchmark {
7378         namespace Detail {
7379             template <typename T, bool Destruct>
7380             struct ObjectStorage
7381             {
7382                 using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7383 
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7384                 ObjectStorage() : data() {}
7385 
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7386                 ObjectStorage(const ObjectStorage& other)
7387                 {
7388                     new(&data) T(other.stored_object());
7389                 }
7390 
ObjectStorageCatch::Benchmark::Detail::ObjectStorage7391                 ObjectStorage(ObjectStorage&& other)
7392                 {
7393                     new(&data) T(std::move(other.stored_object()));
7394                 }
7395 
~ObjectStorageCatch::Benchmark::Detail::ObjectStorage7396                 ~ObjectStorage() { destruct_on_exit<T>(); }
7397 
7398                 template <typename... Args>
constructCatch::Benchmark::Detail::ObjectStorage7399                 void construct(Args&&... args)
7400                 {
7401                     new (&data) T(std::forward<Args>(args)...);
7402                 }
7403 
7404                 template <bool AllowManualDestruction = !Destruct>
destructCatch::Benchmark::Detail::ObjectStorage7405                 typename std::enable_if<AllowManualDestruction>::type destruct()
7406                 {
7407                     stored_object().~T();
7408                 }
7409 
7410             private:
7411                 // If this is a constructor benchmark, destruct the underlying object
7412                 template <typename U>
destruct_on_exitCatch::Benchmark::Detail::ObjectStorage7413                 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7414                 // Otherwise, don't
7415                 template <typename U>
destruct_on_exitCatch::Benchmark::Detail::ObjectStorage7416                 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
7417 
stored_objectCatch::Benchmark::Detail::ObjectStorage7418                 T& stored_object() {
7419                     return *static_cast<T*>(static_cast<void*>(&data));
7420                 }
7421 
stored_objectCatch::Benchmark::Detail::ObjectStorage7422                 T const& stored_object() const {
7423                     return *static_cast<T*>(static_cast<void*>(&data));
7424                 }
7425 
7426                 TStorage data;
7427             };
7428         }
7429 
7430         template <typename T>
7431         using storage_for = Detail::ObjectStorage<T, true>;
7432 
7433         template <typename T>
7434         using destructable_object = Detail::ObjectStorage<T, false>;
7435     }
7436 }
7437 
7438 // end catch_constructor.hpp
7439 // end catch_benchmarking_all.hpp
7440 #endif
7441 
7442 #endif // ! CATCH_CONFIG_IMPL_ONLY
7443 
7444 #ifdef CATCH_IMPL
7445 // start catch_impl.hpp
7446 
7447 #ifdef __clang__
7448 #pragma clang diagnostic push
7449 #pragma clang diagnostic ignored "-Wweak-vtables"
7450 #endif
7451 
7452 // Keep these here for external reporters
7453 // start catch_test_case_tracker.h
7454 
7455 #include <string>
7456 #include <vector>
7457 #include <memory>
7458 
7459 namespace Catch {
7460 namespace TestCaseTracking {
7461 
7462     struct NameAndLocation {
7463         std::string name;
7464         SourceLineInfo location;
7465 
7466         NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
operator ==(NameAndLocation const & lhs,NameAndLocation const & rhs)7467         friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7468             return lhs.name == rhs.name
7469                 && lhs.location == rhs.location;
7470         }
7471     };
7472 
7473     class ITracker;
7474 
7475     using ITrackerPtr = std::shared_ptr<ITracker>;
7476 
7477     class  ITracker {
7478         NameAndLocation m_nameAndLocation;
7479 
7480     public:
ITracker(NameAndLocation const & nameAndLoc)7481         ITracker(NameAndLocation const& nameAndLoc) :
7482             m_nameAndLocation(nameAndLoc)
7483         {}
7484 
7485         // static queries
nameAndLocation() const7486         NameAndLocation const& nameAndLocation() const {
7487             return m_nameAndLocation;
7488         }
7489 
7490         virtual ~ITracker();
7491 
7492         // dynamic queries
7493         virtual bool isComplete() const = 0; // Successfully completed or failed
7494         virtual bool isSuccessfullyCompleted() const = 0;
7495         virtual bool isOpen() const = 0; // Started but not complete
7496         virtual bool hasChildren() const = 0;
7497         virtual bool hasStarted() const = 0;
7498 
7499         virtual ITracker& parent() = 0;
7500 
7501         // actions
7502         virtual void close() = 0; // Successfully complete
7503         virtual void fail() = 0;
7504         virtual void markAsNeedingAnotherRun() = 0;
7505 
7506         virtual void addChild( ITrackerPtr const& child ) = 0;
7507         virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7508         virtual void openChild() = 0;
7509 
7510         // Debug/ checking
7511         virtual bool isSectionTracker() const = 0;
7512         virtual bool isGeneratorTracker() const = 0;
7513     };
7514 
7515     class TrackerContext {
7516 
7517         enum RunState {
7518             NotStarted,
7519             Executing,
7520             CompletedCycle
7521         };
7522 
7523         ITrackerPtr m_rootTracker;
7524         ITracker* m_currentTracker = nullptr;
7525         RunState m_runState = NotStarted;
7526 
7527     public:
7528 
7529         ITracker& startRun();
7530         void endRun();
7531 
7532         void startCycle();
7533         void completeCycle();
7534 
7535         bool completedCycle() const;
7536         ITracker& currentTracker();
7537         void setCurrentTracker( ITracker* tracker );
7538     };
7539 
7540     class TrackerBase : public ITracker {
7541     protected:
7542         enum CycleState {
7543             NotStarted,
7544             Executing,
7545             ExecutingChildren,
7546             NeedsAnotherRun,
7547             CompletedSuccessfully,
7548             Failed
7549         };
7550 
7551         using Children = std::vector<ITrackerPtr>;
7552         TrackerContext& m_ctx;
7553         ITracker* m_parent;
7554         Children m_children;
7555         CycleState m_runState = NotStarted;
7556 
7557     public:
7558         TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7559 
7560         bool isComplete() const override;
7561         bool isSuccessfullyCompleted() const override;
7562         bool isOpen() const override;
7563         bool hasChildren() const override;
hasStarted() const7564         bool hasStarted() const override {
7565             return m_runState != NotStarted;
7566         }
7567 
7568         void addChild( ITrackerPtr const& child ) override;
7569 
7570         ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7571         ITracker& parent() override;
7572 
7573         void openChild() override;
7574 
7575         bool isSectionTracker() const override;
7576         bool isGeneratorTracker() const override;
7577 
7578         void open();
7579 
7580         void close() override;
7581         void fail() override;
7582         void markAsNeedingAnotherRun() override;
7583 
7584     private:
7585         void moveToParent();
7586         void moveToThis();
7587     };
7588 
7589     class SectionTracker : public TrackerBase {
7590         std::vector<std::string> m_filters;
7591         std::string m_trimmed_name;
7592     public:
7593         SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7594 
7595         bool isSectionTracker() const override;
7596 
7597         bool isComplete() const override;
7598 
7599         static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7600 
7601         void tryOpen();
7602 
7603         void addInitialFilters( std::vector<std::string> const& filters );
7604         void addNextFilters( std::vector<std::string> const& filters );
7605         //! Returns filters active in this tracker
7606         std::vector<std::string> const& getFilters() const;
7607         //! Returns whitespace-trimmed name of the tracked section
7608         std::string const& trimmedName() const;
7609     };
7610 
7611 } // namespace TestCaseTracking
7612 
7613 using TestCaseTracking::ITracker;
7614 using TestCaseTracking::TrackerContext;
7615 using TestCaseTracking::SectionTracker;
7616 
7617 } // namespace Catch
7618 
7619 // end catch_test_case_tracker.h
7620 
7621 // start catch_leak_detector.h
7622 
7623 namespace Catch {
7624 
7625     struct LeakDetector {
7626         LeakDetector();
7627         ~LeakDetector();
7628     };
7629 
7630 }
7631 // end catch_leak_detector.h
7632 // Cpp files will be included in the single-header file here
7633 // start catch_stats.cpp
7634 
7635 // Statistical analysis tools
7636 
7637 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7638 
7639 #include <cassert>
7640 #include <random>
7641 
7642 #if defined(CATCH_CONFIG_USE_ASYNC)
7643 #include <future>
7644 #endif
7645 
7646 namespace {
erf_inv(double x)7647     double erf_inv(double x) {
7648         // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7649         double w, p;
7650 
7651         w = -log((1.0 - x) * (1.0 + x));
7652 
7653         if (w < 6.250000) {
7654             w = w - 3.125000;
7655             p = -3.6444120640178196996e-21;
7656             p = -1.685059138182016589e-19 + p * w;
7657             p = 1.2858480715256400167e-18 + p * w;
7658             p = 1.115787767802518096e-17 + p * w;
7659             p = -1.333171662854620906e-16 + p * w;
7660             p = 2.0972767875968561637e-17 + p * w;
7661             p = 6.6376381343583238325e-15 + p * w;
7662             p = -4.0545662729752068639e-14 + p * w;
7663             p = -8.1519341976054721522e-14 + p * w;
7664             p = 2.6335093153082322977e-12 + p * w;
7665             p = -1.2975133253453532498e-11 + p * w;
7666             p = -5.4154120542946279317e-11 + p * w;
7667             p = 1.051212273321532285e-09 + p * w;
7668             p = -4.1126339803469836976e-09 + p * w;
7669             p = -2.9070369957882005086e-08 + p * w;
7670             p = 4.2347877827932403518e-07 + p * w;
7671             p = -1.3654692000834678645e-06 + p * w;
7672             p = -1.3882523362786468719e-05 + p * w;
7673             p = 0.0001867342080340571352 + p * w;
7674             p = -0.00074070253416626697512 + p * w;
7675             p = -0.0060336708714301490533 + p * w;
7676             p = 0.24015818242558961693 + p * w;
7677             p = 1.6536545626831027356 + p * w;
7678         } else if (w < 16.000000) {
7679             w = sqrt(w) - 3.250000;
7680             p = 2.2137376921775787049e-09;
7681             p = 9.0756561938885390979e-08 + p * w;
7682             p = -2.7517406297064545428e-07 + p * w;
7683             p = 1.8239629214389227755e-08 + p * w;
7684             p = 1.5027403968909827627e-06 + p * w;
7685             p = -4.013867526981545969e-06 + p * w;
7686             p = 2.9234449089955446044e-06 + p * w;
7687             p = 1.2475304481671778723e-05 + p * w;
7688             p = -4.7318229009055733981e-05 + p * w;
7689             p = 6.8284851459573175448e-05 + p * w;
7690             p = 2.4031110387097893999e-05 + p * w;
7691             p = -0.0003550375203628474796 + p * w;
7692             p = 0.00095328937973738049703 + p * w;
7693             p = -0.0016882755560235047313 + p * w;
7694             p = 0.0024914420961078508066 + p * w;
7695             p = -0.0037512085075692412107 + p * w;
7696             p = 0.005370914553590063617 + p * w;
7697             p = 1.0052589676941592334 + p * w;
7698             p = 3.0838856104922207635 + p * w;
7699         } else {
7700             w = sqrt(w) - 5.000000;
7701             p = -2.7109920616438573243e-11;
7702             p = -2.5556418169965252055e-10 + p * w;
7703             p = 1.5076572693500548083e-09 + p * w;
7704             p = -3.7894654401267369937e-09 + p * w;
7705             p = 7.6157012080783393804e-09 + p * w;
7706             p = -1.4960026627149240478e-08 + p * w;
7707             p = 2.9147953450901080826e-08 + p * w;
7708             p = -6.7711997758452339498e-08 + p * w;
7709             p = 2.2900482228026654717e-07 + p * w;
7710             p = -9.9298272942317002539e-07 + p * w;
7711             p = 4.5260625972231537039e-06 + p * w;
7712             p = -1.9681778105531670567e-05 + p * w;
7713             p = 7.5995277030017761139e-05 + p * w;
7714             p = -0.00021503011930044477347 + p * w;
7715             p = -0.00013871931833623122026 + p * w;
7716             p = 1.0103004648645343977 + p * w;
7717             p = 4.8499064014085844221 + p * w;
7718         }
7719         return p * x;
7720     }
7721 
standard_deviation(std::vector<double>::iterator first,std::vector<double>::iterator last)7722     double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7723         auto m = Catch::Benchmark::Detail::mean(first, last);
7724         double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7725             double diff = b - m;
7726             return a + diff * diff;
7727             }) / (last - first);
7728             return std::sqrt(variance);
7729     }
7730 
7731 }
7732 
7733 namespace Catch {
7734     namespace Benchmark {
7735         namespace Detail {
7736 
weighted_average_quantile(int k,int q,std::vector<double>::iterator first,std::vector<double>::iterator last)7737             double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7738                 auto count = last - first;
7739                 double idx = (count - 1) * k / static_cast<double>(q);
7740                 int j = static_cast<int>(idx);
7741                 double g = idx - j;
7742                 std::nth_element(first, first + j, last);
7743                 auto xj = first[j];
7744                 if (g == 0) return xj;
7745 
7746                 auto xj1 = *std::min_element(first + (j + 1), last);
7747                 return xj + g * (xj1 - xj);
7748             }
7749 
erfc_inv(double x)7750             double erfc_inv(double x) {
7751                 return erf_inv(1.0 - x);
7752             }
7753 
normal_quantile(double p)7754             double normal_quantile(double p) {
7755                 static const double ROOT_TWO = std::sqrt(2.0);
7756 
7757                 double result = 0.0;
7758                 assert(p >= 0 && p <= 1);
7759                 if (p < 0 || p > 1) {
7760                     return result;
7761                 }
7762 
7763                 result = -erfc_inv(2.0 * p);
7764                 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7765                 result *= /*sd * */ ROOT_TWO;
7766                 // result += normal disttribution mean (0)
7767                 return result;
7768             }
7769 
outlier_variance(Estimate<double> mean,Estimate<double> stddev,int n)7770             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7771                 double sb = stddev.point;
7772                 double mn = mean.point / n;
7773                 double mg_min = mn / 2.;
7774                 double sg = std::min(mg_min / 4., sb / std::sqrt(n));
7775                 double sg2 = sg * sg;
7776                 double sb2 = sb * sb;
7777 
7778                 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7779                     double k = mn - x;
7780                     double d = k * k;
7781                     double nd = n * d;
7782                     double k0 = -n * nd;
7783                     double k1 = sb2 - n * sg2 + nd;
7784                     double det = k1 * k1 - 4 * sg2 * k0;
7785                     return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7786                 };
7787 
7788                 auto var_out = [n, sb2, sg2](double c) {
7789                     double nc = n - c;
7790                     return (nc / n) * (sb2 - nc * sg2);
7791                 };
7792 
7793                 return std::min(var_out(1), var_out(std::min(c_max(0.), c_max(mg_min)))) / sb2;
7794             }
7795 
analyse_samples(double confidence_level,int n_resamples,std::vector<double>::iterator first,std::vector<double>::iterator last)7796             bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7797                 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7798                 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7799                 static std::random_device entropy;
7800                 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7801 
7802                 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7803 
7804                 auto mean = &Detail::mean<std::vector<double>::iterator>;
7805                 auto stddev = &standard_deviation;
7806 
7807 #if defined(CATCH_CONFIG_USE_ASYNC)
7808                 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7809                     auto seed = entropy();
7810                     return std::async(std::launch::async, [=] {
7811                         std::mt19937 rng(seed);
7812                         auto resampled = resample(rng, n_resamples, first, last, f);
7813                         return bootstrap(confidence_level, first, last, resampled, f);
7814                     });
7815                 };
7816 
7817                 auto mean_future = Estimate(mean);
7818                 auto stddev_future = Estimate(stddev);
7819 
7820                 auto mean_estimate = mean_future.get();
7821                 auto stddev_estimate = stddev_future.get();
7822 #else
7823                 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7824                     auto seed = entropy();
7825                     std::mt19937 rng(seed);
7826                     auto resampled = resample(rng, n_resamples, first, last, f);
7827                     return bootstrap(confidence_level, first, last, resampled, f);
7828                 };
7829 
7830                 auto mean_estimate = Estimate(mean);
7831                 auto stddev_estimate = Estimate(stddev);
7832 #endif // CATCH_USE_ASYNC
7833 
7834                 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7835 
7836                 return { mean_estimate, stddev_estimate, outlier_variance };
7837             }
7838         } // namespace Detail
7839     } // namespace Benchmark
7840 } // namespace Catch
7841 
7842 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7843 // end catch_stats.cpp
7844 // start catch_approx.cpp
7845 
7846 #include <cmath>
7847 #include <limits>
7848 
7849 namespace {
7850 
7851 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7852 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)7853 bool marginComparison(double lhs, double rhs, double margin) {
7854     return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7855 }
7856 
7857 }
7858 
7859 namespace Catch {
7860 namespace Detail {
7861 
Approx(double value)7862     Approx::Approx ( double value )
7863     :   m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7864         m_margin( 0.0 ),
7865         m_scale( 0.0 ),
7866         m_value( value )
7867     {}
7868 
custom()7869     Approx Approx::custom() {
7870         return Approx( 0 );
7871     }
7872 
operator -() const7873     Approx Approx::operator-() const {
7874         auto temp(*this);
7875         temp.m_value = -temp.m_value;
7876         return temp;
7877     }
7878 
toString() const7879     std::string Approx::toString() const {
7880         ReusableStringStream rss;
7881         rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7882         return rss.str();
7883     }
7884 
equalityComparisonImpl(const double other) const7885     bool Approx::equalityComparisonImpl(const double other) const {
7886         // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7887         // Thanks to Richard Harris for his help refining the scaled margin value
7888         return marginComparison(m_value, other, m_margin)
7889             || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7890     }
7891 
setMargin(double newMargin)7892     void Approx::setMargin(double newMargin) {
7893         CATCH_ENFORCE(newMargin >= 0,
7894             "Invalid Approx::margin: " << newMargin << '.'
7895             << " Approx::Margin has to be non-negative.");
7896         m_margin = newMargin;
7897     }
7898 
setEpsilon(double newEpsilon)7899     void Approx::setEpsilon(double newEpsilon) {
7900         CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7901             "Invalid Approx::epsilon: " << newEpsilon << '.'
7902             << " Approx::epsilon has to be in [0, 1]");
7903         m_epsilon = newEpsilon;
7904     }
7905 
7906 } // end namespace Detail
7907 
7908 namespace literals {
operator ""_a(long double val)7909     Detail::Approx operator "" _a(long double val) {
7910         return Detail::Approx(val);
7911     }
operator ""_a(unsigned long long val)7912     Detail::Approx operator "" _a(unsigned long long val) {
7913         return Detail::Approx(val);
7914     }
7915 } // end namespace literals
7916 
convert(Catch::Detail::Approx const & value)7917 std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7918     return value.toString();
7919 }
7920 
7921 } // end namespace Catch
7922 // end catch_approx.cpp
7923 // start catch_assertionhandler.cpp
7924 
7925 // start catch_debugger.h
7926 
7927 namespace Catch {
7928     bool isDebuggerActive();
7929 }
7930 
7931 #ifdef CATCH_PLATFORM_MAC
7932 
7933     #if defined(__i386__) || defined(__x86_64__)
7934         #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7935     #elif defined(__aarch64__)
7936         #define CATCH_TRAP()  __asm__(".inst 0xd4200000")
7937     #endif
7938 
7939 #elif defined(CATCH_PLATFORM_IPHONE)
7940 
7941     // use inline assembler
7942     #if defined(__i386__) || defined(__x86_64__)
7943         #define CATCH_TRAP()  __asm__("int $3")
7944     #elif defined(__aarch64__)
7945         #define CATCH_TRAP()  __asm__(".inst 0xd4200000")
7946     #elif defined(__arm__) && !defined(__thumb__)
7947         #define CATCH_TRAP()  __asm__(".inst 0xe7f001f0")
7948     #elif defined(__arm__) &&  defined(__thumb__)
7949         #define CATCH_TRAP()  __asm__(".inst 0xde01")
7950     #endif
7951 
7952 #elif defined(CATCH_PLATFORM_LINUX)
7953     // If we can use inline assembler, do it because this allows us to break
7954     // directly at the location of the failing check instead of breaking inside
7955     // raise() called from it, i.e. one stack frame below.
7956     #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7957         #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7958     #else // Fall back to the generic way.
7959         #include <signal.h>
7960 
7961         #define CATCH_TRAP() raise(SIGTRAP)
7962     #endif
7963 #elif defined(_MSC_VER)
7964     #define CATCH_TRAP() __debugbreak()
7965 #elif defined(__MINGW32__)
7966     extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7967     #define CATCH_TRAP() DebugBreak()
7968 #endif
7969 
7970 #ifndef CATCH_BREAK_INTO_DEBUGGER
7971     #ifdef CATCH_TRAP
7972         #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7973     #else
7974         #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7975     #endif
7976 #endif
7977 
7978 // end catch_debugger.h
7979 // start catch_run_context.h
7980 
7981 // start catch_fatal_condition.h
7982 
7983 // start catch_windows_h_proxy.h
7984 
7985 
7986 #if defined(CATCH_PLATFORM_WINDOWS)
7987 
7988 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
7989 #  define CATCH_DEFINED_NOMINMAX
7990 #  define NOMINMAX
7991 #endif
7992 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
7993 #  define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
7994 #  define WIN32_LEAN_AND_MEAN
7995 #endif
7996 
7997 #ifdef __AFXDLL
7998 #include <AfxWin.h>
7999 #else
8000 #include <windows.h>
8001 #endif
8002 
8003 #ifdef CATCH_DEFINED_NOMINMAX
8004 #  undef NOMINMAX
8005 #endif
8006 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
8007 #  undef WIN32_LEAN_AND_MEAN
8008 #endif
8009 
8010 #endif // defined(CATCH_PLATFORM_WINDOWS)
8011 
8012 // end catch_windows_h_proxy.h
8013 #if defined( CATCH_CONFIG_WINDOWS_SEH )
8014 
8015 namespace Catch {
8016 
8017     struct FatalConditionHandler {
8018 
8019         static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
8020         FatalConditionHandler();
8021         static void reset();
8022         ~FatalConditionHandler();
8023 
8024     private:
8025         static bool isSet;
8026         static ULONG guaranteeSize;
8027         static PVOID exceptionHandlerHandle;
8028     };
8029 
8030 } // namespace Catch
8031 
8032 #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
8033 
8034 #include <signal.h>
8035 
8036 namespace Catch {
8037 
8038     struct FatalConditionHandler {
8039 
8040         static bool isSet;
8041         static struct sigaction oldSigActions[];
8042         static stack_t oldSigStack;
8043         static char altStackMem[];
8044 
8045         static void handleSignal( int sig );
8046 
8047         FatalConditionHandler();
8048         ~FatalConditionHandler();
8049         static void reset();
8050     };
8051 
8052 } // namespace Catch
8053 
8054 #else
8055 
8056 namespace Catch {
8057     struct FatalConditionHandler {
8058         void reset();
8059     };
8060 }
8061 
8062 #endif
8063 
8064 // end catch_fatal_condition.h
8065 #include <string>
8066 
8067 namespace Catch {
8068 
8069     struct IMutableContext;
8070 
8071     ///////////////////////////////////////////////////////////////////////////
8072 
8073     class RunContext : public IResultCapture, public IRunner {
8074 
8075     public:
8076         RunContext( RunContext const& ) = delete;
8077         RunContext& operator =( RunContext const& ) = delete;
8078 
8079         explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8080 
8081         ~RunContext() override;
8082 
8083         void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8084         void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8085 
8086         Totals runTest(TestCase const& testCase);
8087 
8088         IConfigPtr config() const;
8089         IStreamingReporter& reporter() const;
8090 
8091     public: // IResultCapture
8092 
8093         // Assertion handlers
8094         void handleExpr
8095                 (   AssertionInfo const& info,
8096                     ITransientExpression const& expr,
8097                     AssertionReaction& reaction ) override;
8098         void handleMessage
8099                 (   AssertionInfo const& info,
8100                     ResultWas::OfType resultType,
8101                     StringRef const& message,
8102                     AssertionReaction& reaction ) override;
8103         void handleUnexpectedExceptionNotThrown
8104                 (   AssertionInfo const& info,
8105                     AssertionReaction& reaction ) override;
8106         void handleUnexpectedInflightException
8107                 (   AssertionInfo const& info,
8108                     std::string const& message,
8109                     AssertionReaction& reaction ) override;
8110         void handleIncomplete
8111                 (   AssertionInfo const& info ) override;
8112         void handleNonExpr
8113                 (   AssertionInfo const &info,
8114                     ResultWas::OfType resultType,
8115                     AssertionReaction &reaction ) override;
8116 
8117         bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
8118 
8119         void sectionEnded( SectionEndInfo const& endInfo ) override;
8120         void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
8121 
8122         auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
8123 
8124 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8125         void benchmarkPreparing( std::string const& name ) override;
8126         void benchmarkStarting( BenchmarkInfo const& info ) override;
8127         void benchmarkEnded( BenchmarkStats<> const& stats ) override;
8128         void benchmarkFailed( std::string const& error ) override;
8129 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8130 
8131         void pushScopedMessage( MessageInfo const& message ) override;
8132         void popScopedMessage( MessageInfo const& message ) override;
8133 
8134         void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
8135 
8136         std::string getCurrentTestName() const override;
8137 
8138         const AssertionResult* getLastResult() const override;
8139 
8140         void exceptionEarlyReported() override;
8141 
8142         void handleFatalErrorCondition( StringRef message ) override;
8143 
8144         bool lastAssertionPassed() override;
8145 
8146         void assertionPassed() override;
8147 
8148     public:
8149         // !TBD We need to do this another way!
8150         bool aborting() const final;
8151 
8152     private:
8153 
8154         void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8155         void invokeActiveTestCase();
8156 
8157         void resetAssertionInfo();
8158         bool testForMissingAssertions( Counts& assertions );
8159 
8160         void assertionEnded( AssertionResult const& result );
8161         void reportExpr
8162                 (   AssertionInfo const &info,
8163                     ResultWas::OfType resultType,
8164                     ITransientExpression const *expr,
8165                     bool negated );
8166 
8167         void populateReaction( AssertionReaction& reaction );
8168 
8169     private:
8170 
8171         void handleUnfinishedSections();
8172 
8173         TestRunInfo m_runInfo;
8174         IMutableContext& m_context;
8175         TestCase const* m_activeTestCase = nullptr;
8176         ITracker* m_testCaseTracker = nullptr;
8177         Option<AssertionResult> m_lastResult;
8178 
8179         IConfigPtr m_config;
8180         Totals m_totals;
8181         IStreamingReporterPtr m_reporter;
8182         std::vector<MessageInfo> m_messages;
8183         std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8184         AssertionInfo m_lastAssertionInfo;
8185         std::vector<SectionEndInfo> m_unfinishedSections;
8186         std::vector<ITracker*> m_activeSections;
8187         TrackerContext m_trackerContext;
8188         bool m_lastAssertionPassed = false;
8189         bool m_shouldReportUnexpected = true;
8190         bool m_includeSuccessfulResults;
8191     };
8192 
8193     void seedRng(IConfig const& config);
8194     unsigned int rngSeed();
8195 } // end namespace Catch
8196 
8197 // end catch_run_context.h
8198 namespace Catch {
8199 
8200     namespace {
operator <<(std::ostream & os,ITransientExpression const & expr)8201         auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
8202             expr.streamReconstructedExpression( os );
8203             return os;
8204         }
8205     }
8206 
LazyExpression(bool isNegated)8207     LazyExpression::LazyExpression( bool isNegated )
8208     :   m_isNegated( isNegated )
8209     {}
8210 
LazyExpression(LazyExpression const & other)8211     LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8212 
operator bool() const8213     LazyExpression::operator bool() const {
8214         return m_transientExpression != nullptr;
8215     }
8216 
operator <<(std::ostream & os,LazyExpression const & lazyExpr)8217     auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
8218         if( lazyExpr.m_isNegated )
8219             os << "!";
8220 
8221         if( lazyExpr ) {
8222             if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8223                 os << "(" << *lazyExpr.m_transientExpression << ")";
8224             else
8225                 os << *lazyExpr.m_transientExpression;
8226         }
8227         else {
8228             os << "{** error - unchecked empty expression requested **}";
8229         }
8230         return os;
8231     }
8232 
AssertionHandler(StringRef const & macroName,SourceLineInfo const & lineInfo,StringRef capturedExpression,ResultDisposition::Flags resultDisposition)8233     AssertionHandler::AssertionHandler
8234         (   StringRef const& macroName,
8235             SourceLineInfo const& lineInfo,
8236             StringRef capturedExpression,
8237             ResultDisposition::Flags resultDisposition )
8238     :   m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8239         m_resultCapture( getResultCapture() )
8240     {}
8241 
handleExpr(ITransientExpression const & expr)8242     void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
8243         m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8244     }
handleMessage(ResultWas::OfType resultType,StringRef const & message)8245     void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8246         m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8247     }
8248 
allowThrows() const8249     auto AssertionHandler::allowThrows() const -> bool {
8250         return getCurrentContext().getConfig()->allowThrows();
8251     }
8252 
complete()8253     void AssertionHandler::complete() {
8254         setCompleted();
8255         if( m_reaction.shouldDebugBreak ) {
8256 
8257             // If you find your debugger stopping you here then go one level up on the
8258             // call-stack for the code that caused it (typically a failed assertion)
8259 
8260             // (To go back to the test and change execution, jump over the throw, next)
8261             CATCH_BREAK_INTO_DEBUGGER();
8262         }
8263         if (m_reaction.shouldThrow) {
8264 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8265             throw Catch::TestFailureException();
8266 #else
8267             CATCH_ERROR( "Test failure requires aborting test!" );
8268 #endif
8269         }
8270     }
setCompleted()8271     void AssertionHandler::setCompleted() {
8272         m_completed = true;
8273     }
8274 
handleUnexpectedInflightException()8275     void AssertionHandler::handleUnexpectedInflightException() {
8276         m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8277     }
8278 
handleExceptionThrownAsExpected()8279     void AssertionHandler::handleExceptionThrownAsExpected() {
8280         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8281     }
handleExceptionNotThrownAsExpected()8282     void AssertionHandler::handleExceptionNotThrownAsExpected() {
8283         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8284     }
8285 
handleUnexpectedExceptionNotThrown()8286     void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8287         m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8288     }
8289 
handleThrowingCallSkipped()8290     void AssertionHandler::handleThrowingCallSkipped() {
8291         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8292     }
8293 
8294     // This is the overload that takes a string and infers the Equals matcher from it
8295     // 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)8296     void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString  ) {
8297         handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8298     }
8299 
8300 } // namespace Catch
8301 // end catch_assertionhandler.cpp
8302 // start catch_assertionresult.cpp
8303 
8304 namespace Catch {
AssertionResultData(ResultWas::OfType _resultType,LazyExpression const & _lazyExpression)8305     AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
8306         lazyExpression(_lazyExpression),
8307         resultType(_resultType) {}
8308 
reconstructExpression() const8309     std::string AssertionResultData::reconstructExpression() const {
8310 
8311         if( reconstructedExpression.empty() ) {
8312             if( lazyExpression ) {
8313                 ReusableStringStream rss;
8314                 rss << lazyExpression;
8315                 reconstructedExpression = rss.str();
8316             }
8317         }
8318         return reconstructedExpression;
8319     }
8320 
AssertionResult(AssertionInfo const & info,AssertionResultData const & data)8321     AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8322     :   m_info( info ),
8323         m_resultData( data )
8324     {}
8325 
8326     // Result was a success
succeeded() const8327     bool AssertionResult::succeeded() const {
8328         return Catch::isOk( m_resultData.resultType );
8329     }
8330 
8331     // Result was a success, or failure is suppressed
isOk() const8332     bool AssertionResult::isOk() const {
8333         return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8334     }
8335 
getResultType() const8336     ResultWas::OfType AssertionResult::getResultType() const {
8337         return m_resultData.resultType;
8338     }
8339 
hasExpression() const8340     bool AssertionResult::hasExpression() const {
8341         return !m_info.capturedExpression.empty();
8342     }
8343 
hasMessage() const8344     bool AssertionResult::hasMessage() const {
8345         return !m_resultData.message.empty();
8346     }
8347 
getExpression() const8348     std::string AssertionResult::getExpression() const {
8349         // Possibly overallocating by 3 characters should be basically free
8350         std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8351         if (isFalseTest(m_info.resultDisposition)) {
8352             expr += "!(";
8353         }
8354         expr += m_info.capturedExpression;
8355         if (isFalseTest(m_info.resultDisposition)) {
8356             expr += ')';
8357         }
8358         return expr;
8359     }
8360 
getExpressionInMacro() const8361     std::string AssertionResult::getExpressionInMacro() const {
8362         std::string expr;
8363         if( m_info.macroName.empty() )
8364             expr = static_cast<std::string>(m_info.capturedExpression);
8365         else {
8366             expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8367             expr += m_info.macroName;
8368             expr += "( ";
8369             expr += m_info.capturedExpression;
8370             expr += " )";
8371         }
8372         return expr;
8373     }
8374 
hasExpandedExpression() const8375     bool AssertionResult::hasExpandedExpression() const {
8376         return hasExpression() && getExpandedExpression() != getExpression();
8377     }
8378 
getExpandedExpression() const8379     std::string AssertionResult::getExpandedExpression() const {
8380         std::string expr = m_resultData.reconstructExpression();
8381         return expr.empty()
8382                 ? getExpression()
8383                 : expr;
8384     }
8385 
getMessage() const8386     std::string AssertionResult::getMessage() const {
8387         return m_resultData.message;
8388     }
getSourceInfo() const8389     SourceLineInfo AssertionResult::getSourceInfo() const {
8390         return m_info.lineInfo;
8391     }
8392 
getTestMacroName() const8393     StringRef AssertionResult::getTestMacroName() const {
8394         return m_info.macroName;
8395     }
8396 
8397 } // end namespace Catch
8398 // end catch_assertionresult.cpp
8399 // start catch_capture_matchers.cpp
8400 
8401 namespace Catch {
8402 
8403     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8404 
8405     // This is the general overload that takes a any string matcher
8406     // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8407     // the Equals matcher (so the header does not mention matchers)
handleExceptionMatchExpr(AssertionHandler & handler,StringMatcher const & matcher,StringRef const & matcherString)8408     void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString  ) {
8409         std::string exceptionMessage = Catch::translateActiveException();
8410         MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8411         handler.handleExpr( expr );
8412     }
8413 
8414 } // namespace Catch
8415 // end catch_capture_matchers.cpp
8416 // start catch_commandline.cpp
8417 
8418 // start catch_commandline.h
8419 
8420 // start catch_clara.h
8421 
8422 // Use Catch's value for console width (store Clara's off to the side, if present)
8423 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8424 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8425 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8426 #endif
8427 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8428 
8429 #ifdef __clang__
8430 #pragma clang diagnostic push
8431 #pragma clang diagnostic ignored "-Wweak-vtables"
8432 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8433 #pragma clang diagnostic ignored "-Wshadow"
8434 #endif
8435 
8436 // start clara.hpp
8437 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8438 //
8439 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8440 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8441 //
8442 // See https://github.com/philsquared/Clara for more details
8443 
8444 // Clara v1.1.5
8445 
8446 
8447 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8448 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8449 #endif
8450 
8451 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8452 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8453 #endif
8454 
8455 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8456 #ifdef __has_include
8457 #if __has_include(<optional>) && __cplusplus >= 201703L
8458 #include <optional>
8459 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8460 #endif
8461 #endif
8462 #endif
8463 
8464 // ----------- #included from clara_textflow.hpp -----------
8465 
8466 // TextFlowCpp
8467 //
8468 // A single-header library for wrapping and laying out basic text, by Phil Nash
8469 //
8470 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8471 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8472 //
8473 // This project is hosted at https://github.com/philsquared/textflowcpp
8474 
8475 
8476 #include <cassert>
8477 #include <ostream>
8478 #include <sstream>
8479 #include <vector>
8480 
8481 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8482 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8483 #endif
8484 
8485 namespace Catch {
8486 namespace clara {
8487 namespace TextFlow {
8488 
isWhitespace(char c)8489 inline auto isWhitespace(char c) -> bool {
8490 	static std::string chars = " \t\n\r";
8491 	return chars.find(c) != std::string::npos;
8492 }
isBreakableBefore(char c)8493 inline auto isBreakableBefore(char c) -> bool {
8494 	static std::string chars = "[({<|";
8495 	return chars.find(c) != std::string::npos;
8496 }
isBreakableAfter(char c)8497 inline auto isBreakableAfter(char c) -> bool {
8498 	static std::string chars = "])}>.,:;*+-=&/\\";
8499 	return chars.find(c) != std::string::npos;
8500 }
8501 
8502 class Columns;
8503 
8504 class Column {
8505 	std::vector<std::string> m_strings;
8506 	size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8507 	size_t m_indent = 0;
8508 	size_t m_initialIndent = std::string::npos;
8509 
8510 public:
8511 	class iterator {
8512 		friend Column;
8513 
8514 		Column const& m_column;
8515 		size_t m_stringIndex = 0;
8516 		size_t m_pos = 0;
8517 
8518 		size_t m_len = 0;
8519 		size_t m_end = 0;
8520 		bool m_suffix = false;
8521 
iterator(Column const & column,size_t stringIndex)8522 		iterator(Column const& column, size_t stringIndex)
8523 			: m_column(column),
8524 			m_stringIndex(stringIndex) {}
8525 
line() const8526 		auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8527 
isBoundary(size_t at) const8528 		auto isBoundary(size_t at) const -> bool {
8529 			assert(at > 0);
8530 			assert(at <= line().size());
8531 
8532 			return at == line().size() ||
8533 				(isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8534 				isBreakableBefore(line()[at]) ||
8535 				isBreakableAfter(line()[at - 1]);
8536 		}
8537 
calcLength()8538 		void calcLength() {
8539 			assert(m_stringIndex < m_column.m_strings.size());
8540 
8541 			m_suffix = false;
8542 			auto width = m_column.m_width - indent();
8543 			m_end = m_pos;
8544 			if (line()[m_pos] == '\n') {
8545 				++m_end;
8546 			}
8547 			while (m_end < line().size() && line()[m_end] != '\n')
8548 				++m_end;
8549 
8550 			if (m_end < m_pos + width) {
8551 				m_len = m_end - m_pos;
8552 			} else {
8553 				size_t len = width;
8554 				while (len > 0 && !isBoundary(m_pos + len))
8555 					--len;
8556 				while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8557 					--len;
8558 
8559 				if (len > 0) {
8560 					m_len = len;
8561 				} else {
8562 					m_suffix = true;
8563 					m_len = width - 1;
8564 				}
8565 			}
8566 		}
8567 
indent() const8568 		auto indent() const -> size_t {
8569 			auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8570 			return initial == std::string::npos ? m_column.m_indent : initial;
8571 		}
8572 
addIndentAndSuffix(std::string const & plain) const8573 		auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8574 			return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8575 		}
8576 
8577 	public:
8578 		using difference_type = std::ptrdiff_t;
8579 		using value_type = std::string;
8580 		using pointer = value_type * ;
8581 		using reference = value_type & ;
8582 		using iterator_category = std::forward_iterator_tag;
8583 
iterator(Column const & column)8584 		explicit iterator(Column const& column) : m_column(column) {
8585 			assert(m_column.m_width > m_column.m_indent);
8586 			assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8587 			calcLength();
8588 			if (m_len == 0)
8589 				m_stringIndex++; // Empty string
8590 		}
8591 
operator *() const8592 		auto operator *() const -> std::string {
8593 			assert(m_stringIndex < m_column.m_strings.size());
8594 			assert(m_pos <= m_end);
8595 			return addIndentAndSuffix(line().substr(m_pos, m_len));
8596 		}
8597 
operator ++()8598 		auto operator ++() -> iterator& {
8599 			m_pos += m_len;
8600 			if (m_pos < line().size() && line()[m_pos] == '\n')
8601 				m_pos += 1;
8602 			else
8603 				while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8604 					++m_pos;
8605 
8606 			if (m_pos == line().size()) {
8607 				m_pos = 0;
8608 				++m_stringIndex;
8609 			}
8610 			if (m_stringIndex < m_column.m_strings.size())
8611 				calcLength();
8612 			return *this;
8613 		}
operator ++(int)8614 		auto operator ++(int) -> iterator {
8615 			iterator prev(*this);
8616 			operator++();
8617 			return prev;
8618 		}
8619 
operator ==(iterator const & other) const8620 		auto operator ==(iterator const& other) const -> bool {
8621 			return
8622 				m_pos == other.m_pos &&
8623 				m_stringIndex == other.m_stringIndex &&
8624 				&m_column == &other.m_column;
8625 		}
operator !=(iterator const & other) const8626 		auto operator !=(iterator const& other) const -> bool {
8627 			return !operator==(other);
8628 		}
8629 	};
8630 	using const_iterator = iterator;
8631 
Column(std::string const & text)8632 	explicit Column(std::string const& text) { m_strings.push_back(text); }
8633 
width(size_t newWidth)8634 	auto width(size_t newWidth) -> Column& {
8635 		assert(newWidth > 0);
8636 		m_width = newWidth;
8637 		return *this;
8638 	}
indent(size_t newIndent)8639 	auto indent(size_t newIndent) -> Column& {
8640 		m_indent = newIndent;
8641 		return *this;
8642 	}
initialIndent(size_t newIndent)8643 	auto initialIndent(size_t newIndent) -> Column& {
8644 		m_initialIndent = newIndent;
8645 		return *this;
8646 	}
8647 
width() const8648 	auto width() const -> size_t { return m_width; }
begin() const8649 	auto begin() const -> iterator { return iterator(*this); }
end() const8650 	auto end() const -> iterator { return { *this, m_strings.size() }; }
8651 
operator <<(std::ostream & os,Column const & col)8652 	inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8653 		bool first = true;
8654 		for (auto line : col) {
8655 			if (first)
8656 				first = false;
8657 			else
8658 				os << "\n";
8659 			os << line;
8660 		}
8661 		return os;
8662 	}
8663 
8664 	auto operator + (Column const& other)->Columns;
8665 
toString() const8666 	auto toString() const -> std::string {
8667 		std::ostringstream oss;
8668 		oss << *this;
8669 		return oss.str();
8670 	}
8671 };
8672 
8673 class Spacer : public Column {
8674 
8675 public:
Spacer(size_t spaceWidth)8676 	explicit Spacer(size_t spaceWidth) : Column("") {
8677 		width(spaceWidth);
8678 	}
8679 };
8680 
8681 class Columns {
8682 	std::vector<Column> m_columns;
8683 
8684 public:
8685 
8686 	class iterator {
8687 		friend Columns;
8688 		struct EndTag {};
8689 
8690 		std::vector<Column> const& m_columns;
8691 		std::vector<Column::iterator> m_iterators;
8692 		size_t m_activeIterators;
8693 
iterator(Columns const & columns,EndTag)8694 		iterator(Columns const& columns, EndTag)
8695 			: m_columns(columns.m_columns),
8696 			m_activeIterators(0) {
8697 			m_iterators.reserve(m_columns.size());
8698 
8699 			for (auto const& col : m_columns)
8700 				m_iterators.push_back(col.end());
8701 		}
8702 
8703 	public:
8704 		using difference_type = std::ptrdiff_t;
8705 		using value_type = std::string;
8706 		using pointer = value_type * ;
8707 		using reference = value_type & ;
8708 		using iterator_category = std::forward_iterator_tag;
8709 
iterator(Columns const & columns)8710 		explicit iterator(Columns const& columns)
8711 			: m_columns(columns.m_columns),
8712 			m_activeIterators(m_columns.size()) {
8713 			m_iterators.reserve(m_columns.size());
8714 
8715 			for (auto const& col : m_columns)
8716 				m_iterators.push_back(col.begin());
8717 		}
8718 
operator ==(iterator const & other) const8719 		auto operator ==(iterator const& other) const -> bool {
8720 			return m_iterators == other.m_iterators;
8721 		}
operator !=(iterator const & other) const8722 		auto operator !=(iterator const& other) const -> bool {
8723 			return m_iterators != other.m_iterators;
8724 		}
operator *() const8725 		auto operator *() const -> std::string {
8726 			std::string row, padding;
8727 
8728 			for (size_t i = 0; i < m_columns.size(); ++i) {
8729 				auto width = m_columns[i].width();
8730 				if (m_iterators[i] != m_columns[i].end()) {
8731 					std::string col = *m_iterators[i];
8732 					row += padding + col;
8733 					if (col.size() < width)
8734 						padding = std::string(width - col.size(), ' ');
8735 					else
8736 						padding = "";
8737 				} else {
8738 					padding += std::string(width, ' ');
8739 				}
8740 			}
8741 			return row;
8742 		}
operator ++()8743 		auto operator ++() -> iterator& {
8744 			for (size_t i = 0; i < m_columns.size(); ++i) {
8745 				if (m_iterators[i] != m_columns[i].end())
8746 					++m_iterators[i];
8747 			}
8748 			return *this;
8749 		}
operator ++(int)8750 		auto operator ++(int) -> iterator {
8751 			iterator prev(*this);
8752 			operator++();
8753 			return prev;
8754 		}
8755 	};
8756 	using const_iterator = iterator;
8757 
begin() const8758 	auto begin() const -> iterator { return iterator(*this); }
end() const8759 	auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8760 
operator +=(Column const & col)8761 	auto operator += (Column const& col) -> Columns& {
8762 		m_columns.push_back(col);
8763 		return *this;
8764 	}
operator +(Column const & col)8765 	auto operator + (Column const& col) -> Columns {
8766 		Columns combined = *this;
8767 		combined += col;
8768 		return combined;
8769 	}
8770 
operator <<(std::ostream & os,Columns const & cols)8771 	inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8772 
8773 		bool first = true;
8774 		for (auto line : cols) {
8775 			if (first)
8776 				first = false;
8777 			else
8778 				os << "\n";
8779 			os << line;
8780 		}
8781 		return os;
8782 	}
8783 
toString() const8784 	auto toString() const -> std::string {
8785 		std::ostringstream oss;
8786 		oss << *this;
8787 		return oss.str();
8788 	}
8789 };
8790 
operator +(Column const & other)8791 inline auto Column::operator + (Column const& other) -> Columns {
8792 	Columns cols;
8793 	cols += *this;
8794 	cols += other;
8795 	return cols;
8796 }
8797 }
8798 
8799 }
8800 }
8801 
8802 // ----------- end of #include from clara_textflow.hpp -----------
8803 // ........... back in clara.hpp
8804 
8805 #include <cctype>
8806 #include <string>
8807 #include <memory>
8808 #include <set>
8809 #include <algorithm>
8810 
8811 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8812 #define CATCH_PLATFORM_WINDOWS
8813 #endif
8814 
8815 namespace Catch { namespace clara {
8816 namespace detail {
8817 
8818     // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8819     template<typename L>
8820     struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8821 
8822     template<typename ClassT, typename ReturnT, typename... Args>
8823     struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8824         static const bool isValid = false;
8825     };
8826 
8827     template<typename ClassT, typename ReturnT, typename ArgT>
8828     struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8829         static const bool isValid = true;
8830         using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8831         using ReturnType = ReturnT;
8832     };
8833 
8834     class TokenStream;
8835 
8836     // Transport for raw args (copied from main args, or supplied via init list for testing)
8837     class Args {
8838         friend TokenStream;
8839         std::string m_exeName;
8840         std::vector<std::string> m_args;
8841 
8842     public:
Args(int argc,char const * const * argv)8843         Args( int argc, char const* const* argv )
8844             : m_exeName(argv[0]),
8845               m_args(argv + 1, argv + argc) {}
8846 
Args(std::initializer_list<std::string> args)8847         Args( std::initializer_list<std::string> args )
8848         :   m_exeName( *args.begin() ),
8849             m_args( args.begin()+1, args.end() )
8850         {}
8851 
exeName() const8852         auto exeName() const -> std::string {
8853             return m_exeName;
8854         }
8855     };
8856 
8857     // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8858     // may encode an option + its argument if the : or = form is used
8859     enum class TokenType {
8860         Option, Argument
8861     };
8862     struct Token {
8863         TokenType type;
8864         std::string token;
8865     };
8866 
isOptPrefix(char c)8867     inline auto isOptPrefix( char c ) -> bool {
8868         return c == '-'
8869 #ifdef CATCH_PLATFORM_WINDOWS
8870             || c == '/'
8871 #endif
8872         ;
8873     }
8874 
8875     // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8876     class TokenStream {
8877         using Iterator = std::vector<std::string>::const_iterator;
8878         Iterator it;
8879         Iterator itEnd;
8880         std::vector<Token> m_tokenBuffer;
8881 
loadBuffer()8882         void loadBuffer() {
8883             m_tokenBuffer.resize( 0 );
8884 
8885             // Skip any empty strings
8886             while( it != itEnd && it->empty() )
8887                 ++it;
8888 
8889             if( it != itEnd ) {
8890                 auto const &next = *it;
8891                 if( isOptPrefix( next[0] ) ) {
8892                     auto delimiterPos = next.find_first_of( " :=" );
8893                     if( delimiterPos != std::string::npos ) {
8894                         m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8895                         m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8896                     } else {
8897                         if( next[1] != '-' && next.size() > 2 ) {
8898                             std::string opt = "- ";
8899                             for( size_t i = 1; i < next.size(); ++i ) {
8900                                 opt[1] = next[i];
8901                                 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8902                             }
8903                         } else {
8904                             m_tokenBuffer.push_back( { TokenType::Option, next } );
8905                         }
8906                     }
8907                 } else {
8908                     m_tokenBuffer.push_back( { TokenType::Argument, next } );
8909                 }
8910             }
8911         }
8912 
8913     public:
TokenStream(Args const & args)8914         explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8915 
TokenStream(Iterator it,Iterator itEnd)8916         TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8917             loadBuffer();
8918         }
8919 
operator bool() const8920         explicit operator bool() const {
8921             return !m_tokenBuffer.empty() || it != itEnd;
8922         }
8923 
count() const8924         auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8925 
operator *() const8926         auto operator*() const -> Token {
8927             assert( !m_tokenBuffer.empty() );
8928             return m_tokenBuffer.front();
8929         }
8930 
operator ->() const8931         auto operator->() const -> Token const * {
8932             assert( !m_tokenBuffer.empty() );
8933             return &m_tokenBuffer.front();
8934         }
8935 
operator ++()8936         auto operator++() -> TokenStream & {
8937             if( m_tokenBuffer.size() >= 2 ) {
8938                 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8939             } else {
8940                 if( it != itEnd )
8941                     ++it;
8942                 loadBuffer();
8943             }
8944             return *this;
8945         }
8946     };
8947 
8948     class ResultBase {
8949     public:
8950         enum Type {
8951             Ok, LogicError, RuntimeError
8952         };
8953 
8954     protected:
ResultBase(Type type)8955         ResultBase( Type type ) : m_type( type ) {}
8956         virtual ~ResultBase() = default;
8957 
8958         virtual void enforceOk() const = 0;
8959 
8960         Type m_type;
8961     };
8962 
8963     template<typename T>
8964     class ResultValueBase : public ResultBase {
8965     public:
value() const8966         auto value() const -> T const & {
8967             enforceOk();
8968             return m_value;
8969         }
8970 
8971     protected:
ResultValueBase(Type type)8972         ResultValueBase( Type type ) : ResultBase( type ) {}
8973 
ResultValueBase(ResultValueBase const & other)8974         ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8975             if( m_type == ResultBase::Ok )
8976                 new( &m_value ) T( other.m_value );
8977         }
8978 
ResultValueBase(Type,T const & value)8979         ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8980             new( &m_value ) T( value );
8981         }
8982 
operator =(ResultValueBase const & other)8983         auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8984             if( m_type == ResultBase::Ok )
8985                 m_value.~T();
8986             ResultBase::operator=(other);
8987             if( m_type == ResultBase::Ok )
8988                 new( &m_value ) T( other.m_value );
8989             return *this;
8990         }
8991 
~ResultValueBase()8992         ~ResultValueBase() override {
8993             if( m_type == Ok )
8994                 m_value.~T();
8995         }
8996 
8997         union {
8998             T m_value;
8999         };
9000     };
9001 
9002     template<>
9003     class ResultValueBase<void> : public ResultBase {
9004     protected:
9005         using ResultBase::ResultBase;
9006     };
9007 
9008     template<typename T = void>
9009     class BasicResult : public ResultValueBase<T> {
9010     public:
9011         template<typename U>
BasicResult(BasicResult<U> const & other)9012         explicit BasicResult( BasicResult<U> const &other )
9013         :   ResultValueBase<T>( other.type() ),
9014             m_errorMessage( other.errorMessage() )
9015         {
9016             assert( type() != ResultBase::Ok );
9017         }
9018 
9019         template<typename U>
ok(U const & value)9020         static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
ok()9021         static auto ok() -> BasicResult { return { ResultBase::Ok }; }
logicError(std::string const & message)9022         static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
runtimeError(std::string const & message)9023         static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
9024 
operator bool() const9025         explicit operator bool() const { return m_type == ResultBase::Ok; }
type() const9026         auto type() const -> ResultBase::Type { return m_type; }
errorMessage() const9027         auto errorMessage() const -> std::string { return m_errorMessage; }
9028 
9029     protected:
enforceOk() const9030         void enforceOk() const override {
9031 
9032             // Errors shouldn't reach this point, but if they do
9033             // the actual error message will be in m_errorMessage
9034             assert( m_type != ResultBase::LogicError );
9035             assert( m_type != ResultBase::RuntimeError );
9036             if( m_type != ResultBase::Ok )
9037                 std::abort();
9038         }
9039 
9040         std::string m_errorMessage; // Only populated if resultType is an error
9041 
BasicResult(ResultBase::Type type,std::string const & message)9042         BasicResult( ResultBase::Type type, std::string const &message )
9043         :   ResultValueBase<T>(type),
9044             m_errorMessage(message)
9045         {
9046             assert( m_type != ResultBase::Ok );
9047         }
9048 
9049         using ResultValueBase<T>::ResultValueBase;
9050         using ResultBase::m_type;
9051     };
9052 
9053     enum class ParseResultType {
9054         Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9055     };
9056 
9057     class ParseState {
9058     public:
9059 
ParseState(ParseResultType type,TokenStream const & remainingTokens)9060         ParseState( ParseResultType type, TokenStream const &remainingTokens )
9061         : m_type(type),
9062           m_remainingTokens( remainingTokens )
9063         {}
9064 
type() const9065         auto type() const -> ParseResultType { return m_type; }
remainingTokens() const9066         auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9067 
9068     private:
9069         ParseResultType m_type;
9070         TokenStream m_remainingTokens;
9071     };
9072 
9073     using Result = BasicResult<void>;
9074     using ParserResult = BasicResult<ParseResultType>;
9075     using InternalParseResult = BasicResult<ParseState>;
9076 
9077     struct HelpColumns {
9078         std::string left;
9079         std::string right;
9080     };
9081 
9082     template<typename T>
convertInto(std::string const & source,T & target)9083     inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
9084         std::stringstream ss;
9085         ss << source;
9086         ss >> target;
9087         if( ss.fail() )
9088             return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
9089         else
9090             return ParserResult::ok( ParseResultType::Matched );
9091     }
convertInto(std::string const & source,std::string & target)9092     inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
9093         target = source;
9094         return ParserResult::ok( ParseResultType::Matched );
9095     }
convertInto(std::string const & source,bool & target)9096     inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
9097         std::string srcLC = source;
9098         std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9099         if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9100             target = true;
9101         else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9102             target = false;
9103         else
9104             return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
9105         return ParserResult::ok( ParseResultType::Matched );
9106     }
9107 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9108     template<typename T>
convertInto(std::string const & source,CLARA_CONFIG_OPTIONAL_TYPE<T> & target)9109     inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9110         T temp;
9111         auto result = convertInto( source, temp );
9112         if( result )
9113             target = std::move(temp);
9114         return result;
9115     }
9116 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9117 
9118     struct NonCopyable {
9119         NonCopyable() = default;
9120         NonCopyable( NonCopyable const & ) = delete;
9121         NonCopyable( NonCopyable && ) = delete;
9122         NonCopyable &operator=( NonCopyable const & ) = delete;
9123         NonCopyable &operator=( NonCopyable && ) = delete;
9124     };
9125 
9126     struct BoundRef : NonCopyable {
9127         virtual ~BoundRef() = default;
isContainerCatch::clara::detail::BoundRef9128         virtual auto isContainer() const -> bool { return false; }
isFlagCatch::clara::detail::BoundRef9129         virtual auto isFlag() const -> bool { return false; }
9130     };
9131     struct BoundValueRefBase : BoundRef {
9132         virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
9133     };
9134     struct BoundFlagRefBase : BoundRef {
9135         virtual auto setFlag( bool flag ) -> ParserResult = 0;
isFlagCatch::clara::detail::BoundFlagRefBase9136         virtual auto isFlag() const -> bool { return true; }
9137     };
9138 
9139     template<typename T>
9140     struct BoundValueRef : BoundValueRefBase {
9141         T &m_ref;
9142 
BoundValueRefCatch::clara::detail::BoundValueRef9143         explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9144 
setValueCatch::clara::detail::BoundValueRef9145         auto setValue( std::string const &arg ) -> ParserResult override {
9146             return convertInto( arg, m_ref );
9147         }
9148     };
9149 
9150     template<typename T>
9151     struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9152         std::vector<T> &m_ref;
9153 
BoundValueRefCatch::clara::detail::BoundValueRef9154         explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9155 
isContainerCatch::clara::detail::BoundValueRef9156         auto isContainer() const -> bool override { return true; }
9157 
setValueCatch::clara::detail::BoundValueRef9158         auto setValue( std::string const &arg ) -> ParserResult override {
9159             T temp;
9160             auto result = convertInto( arg, temp );
9161             if( result )
9162                 m_ref.push_back( temp );
9163             return result;
9164         }
9165     };
9166 
9167     struct BoundFlagRef : BoundFlagRefBase {
9168         bool &m_ref;
9169 
BoundFlagRefCatch::clara::detail::BoundFlagRef9170         explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
9171 
setFlagCatch::clara::detail::BoundFlagRef9172         auto setFlag( bool flag ) -> ParserResult override {
9173             m_ref = flag;
9174             return ParserResult::ok( ParseResultType::Matched );
9175         }
9176     };
9177 
9178     template<typename ReturnType>
9179     struct LambdaInvoker {
9180         static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
9181 
9182         template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker9183         static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9184             return lambda( arg );
9185         }
9186     };
9187 
9188     template<>
9189     struct LambdaInvoker<void> {
9190         template<typename L, typename ArgType>
invokeCatch::clara::detail::LambdaInvoker9191         static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9192             lambda( arg );
9193             return ParserResult::ok( ParseResultType::Matched );
9194         }
9195     };
9196 
9197     template<typename ArgType, typename L>
invokeLambda(L const & lambda,std::string const & arg)9198     inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
9199         ArgType temp{};
9200         auto result = convertInto( arg, temp );
9201         return !result
9202            ? result
9203            : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9204     }
9205 
9206     template<typename L>
9207     struct BoundLambda : BoundValueRefBase {
9208         L m_lambda;
9209 
9210         static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
BoundLambdaCatch::clara::detail::BoundLambda9211         explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
9212 
setValueCatch::clara::detail::BoundLambda9213         auto setValue( std::string const &arg ) -> ParserResult override {
9214             return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9215         }
9216     };
9217 
9218     template<typename L>
9219     struct BoundFlagLambda : BoundFlagRefBase {
9220         L m_lambda;
9221 
9222         static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9223         static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
9224 
BoundFlagLambdaCatch::clara::detail::BoundFlagLambda9225         explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
9226 
setFlagCatch::clara::detail::BoundFlagLambda9227         auto setFlag( bool flag ) -> ParserResult override {
9228             return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9229         }
9230     };
9231 
9232     enum class Optionality { Optional, Required };
9233 
9234     struct Parser;
9235 
9236     class ParserBase {
9237     public:
9238         virtual ~ParserBase() = default;
validate() const9239         virtual auto validate() const -> Result { return Result::ok(); }
9240         virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult  = 0;
cardinality() const9241         virtual auto cardinality() const -> size_t { return 1; }
9242 
parse(Args const & args) const9243         auto parse( Args const &args ) const -> InternalParseResult {
9244             return parse( args.exeName(), TokenStream( args ) );
9245         }
9246     };
9247 
9248     template<typename DerivedT>
9249     class ComposableParserImpl : public ParserBase {
9250     public:
9251         template<typename T>
9252         auto operator|( T const &other ) const -> Parser;
9253 
9254 		template<typename T>
9255         auto operator+( T const &other ) const -> Parser;
9256     };
9257 
9258     // Common code and state for Args and Opts
9259     template<typename DerivedT>
9260     class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9261     protected:
9262         Optionality m_optionality = Optionality::Optional;
9263         std::shared_ptr<BoundRef> m_ref;
9264         std::string m_hint;
9265         std::string m_description;
9266 
ParserRefImpl(std::shared_ptr<BoundRef> const & ref)9267         explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
9268 
9269     public:
9270         template<typename T>
ParserRefImpl(T & ref,std::string const & hint)9271         ParserRefImpl( T &ref, std::string const &hint )
9272         :   m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9273             m_hint( hint )
9274         {}
9275 
9276         template<typename LambdaT>
ParserRefImpl(LambdaT const & ref,std::string const & hint)9277         ParserRefImpl( LambdaT const &ref, std::string const &hint )
9278         :   m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9279             m_hint(hint)
9280         {}
9281 
operator ()(std::string const & description)9282         auto operator()( std::string const &description ) -> DerivedT & {
9283             m_description = description;
9284             return static_cast<DerivedT &>( *this );
9285         }
9286 
optional()9287         auto optional() -> DerivedT & {
9288             m_optionality = Optionality::Optional;
9289             return static_cast<DerivedT &>( *this );
9290         };
9291 
required()9292         auto required() -> DerivedT & {
9293             m_optionality = Optionality::Required;
9294             return static_cast<DerivedT &>( *this );
9295         };
9296 
isOptional() const9297         auto isOptional() const -> bool {
9298             return m_optionality == Optionality::Optional;
9299         }
9300 
cardinality() const9301         auto cardinality() const -> size_t override {
9302             if( m_ref->isContainer() )
9303                 return 0;
9304             else
9305                 return 1;
9306         }
9307 
hint() const9308         auto hint() const -> std::string { return m_hint; }
9309     };
9310 
9311     class ExeName : public ComposableParserImpl<ExeName> {
9312         std::shared_ptr<std::string> m_name;
9313         std::shared_ptr<BoundValueRefBase> m_ref;
9314 
9315         template<typename LambdaT>
makeRef(LambdaT const & lambda)9316         static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9317             return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9318         }
9319 
9320     public:
ExeName()9321         ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
9322 
ExeName(std::string & ref)9323         explicit ExeName( std::string &ref ) : ExeName() {
9324             m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9325         }
9326 
9327         template<typename LambdaT>
ExeName(LambdaT const & lambda)9328         explicit ExeName( LambdaT const& lambda ) : ExeName() {
9329             m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9330         }
9331 
9332         // The exe name is not parsed out of the normal tokens, but is handled specially
parse(std::string const &,TokenStream const & tokens) const9333         auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9334             return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9335         }
9336 
name() const9337         auto name() const -> std::string { return *m_name; }
set(std::string const & newName)9338         auto set( std::string const& newName ) -> ParserResult {
9339 
9340             auto lastSlash = newName.find_last_of( "\\/" );
9341             auto filename = ( lastSlash == std::string::npos )
9342                     ? newName
9343                     : newName.substr( lastSlash+1 );
9344 
9345             *m_name = filename;
9346             if( m_ref )
9347                 return m_ref->setValue( filename );
9348             else
9349                 return ParserResult::ok( ParseResultType::Matched );
9350         }
9351     };
9352 
9353     class Arg : public ParserRefImpl<Arg> {
9354     public:
9355         using ParserRefImpl::ParserRefImpl;
9356 
parse(std::string const &,TokenStream const & tokens) const9357         auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9358             auto validationResult = validate();
9359             if( !validationResult )
9360                 return InternalParseResult( validationResult );
9361 
9362             auto remainingTokens = tokens;
9363             auto const &token = *remainingTokens;
9364             if( token.type != TokenType::Argument )
9365                 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9366 
9367             assert( !m_ref->isFlag() );
9368             auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9369 
9370             auto result = valueRef->setValue( remainingTokens->token );
9371             if( !result )
9372                 return InternalParseResult( result );
9373             else
9374                 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9375         }
9376     };
9377 
normaliseOpt(std::string const & optName)9378     inline auto normaliseOpt( std::string const &optName ) -> std::string {
9379 #ifdef CATCH_PLATFORM_WINDOWS
9380         if( optName[0] == '/' )
9381             return "-" + optName.substr( 1 );
9382         else
9383 #endif
9384             return optName;
9385     }
9386 
9387     class Opt : public ParserRefImpl<Opt> {
9388     protected:
9389         std::vector<std::string> m_optNames;
9390 
9391     public:
9392         template<typename LambdaT>
Opt(LambdaT const & ref)9393         explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9394 
Opt(bool & ref)9395         explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9396 
9397         template<typename LambdaT>
Opt(LambdaT const & ref,std::string const & hint)9398         Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9399 
9400         template<typename T>
Opt(T & ref,std::string const & hint)9401         Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9402 
operator [](std::string const & optName)9403         auto operator[]( std::string const &optName ) -> Opt & {
9404             m_optNames.push_back( optName );
9405             return *this;
9406         }
9407 
getHelpColumns() const9408         auto getHelpColumns() const -> std::vector<HelpColumns> {
9409             std::ostringstream oss;
9410             bool first = true;
9411             for( auto const &opt : m_optNames ) {
9412                 if (first)
9413                     first = false;
9414                 else
9415                     oss << ", ";
9416                 oss << opt;
9417             }
9418             if( !m_hint.empty() )
9419                 oss << " <" << m_hint << ">";
9420             return { { oss.str(), m_description } };
9421         }
9422 
isMatch(std::string const & optToken) const9423         auto isMatch( std::string const &optToken ) const -> bool {
9424             auto normalisedToken = normaliseOpt( optToken );
9425             for( auto const &name : m_optNames ) {
9426                 if( normaliseOpt( name ) == normalisedToken )
9427                     return true;
9428             }
9429             return false;
9430         }
9431 
9432         using ParserBase::parse;
9433 
parse(std::string const &,TokenStream const & tokens) const9434         auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9435             auto validationResult = validate();
9436             if( !validationResult )
9437                 return InternalParseResult( validationResult );
9438 
9439             auto remainingTokens = tokens;
9440             if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9441                 auto const &token = *remainingTokens;
9442                 if( isMatch(token.token ) ) {
9443                     if( m_ref->isFlag() ) {
9444                         auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9445                         auto result = flagRef->setFlag( true );
9446                         if( !result )
9447                             return InternalParseResult( result );
9448                         if( result.value() == ParseResultType::ShortCircuitAll )
9449                             return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9450                     } else {
9451                         auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9452                         ++remainingTokens;
9453                         if( !remainingTokens )
9454                             return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9455                         auto const &argToken = *remainingTokens;
9456                         if( argToken.type != TokenType::Argument )
9457                             return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9458                         auto result = valueRef->setValue( argToken.token );
9459                         if( !result )
9460                             return InternalParseResult( result );
9461                         if( result.value() == ParseResultType::ShortCircuitAll )
9462                             return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9463                     }
9464                     return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9465                 }
9466             }
9467             return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9468         }
9469 
validate() const9470         auto validate() const -> Result override {
9471             if( m_optNames.empty() )
9472                 return Result::logicError( "No options supplied to Opt" );
9473             for( auto const &name : m_optNames ) {
9474                 if( name.empty() )
9475                     return Result::logicError( "Option name cannot be empty" );
9476 #ifdef CATCH_PLATFORM_WINDOWS
9477                 if( name[0] != '-' && name[0] != '/' )
9478                     return Result::logicError( "Option name must begin with '-' or '/'" );
9479 #else
9480                 if( name[0] != '-' )
9481                     return Result::logicError( "Option name must begin with '-'" );
9482 #endif
9483             }
9484             return ParserRefImpl::validate();
9485         }
9486     };
9487 
9488     struct Help : Opt {
HelpCatch::clara::detail::Help9489         Help( bool &showHelpFlag )
9490         :   Opt([&]( bool flag ) {
9491                 showHelpFlag = flag;
9492                 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9493             })
9494         {
9495             static_cast<Opt &>( *this )
9496                     ("display usage information")
9497                     ["-?"]["-h"]["--help"]
9498                     .optional();
9499         }
9500     };
9501 
9502     struct Parser : ParserBase {
9503 
9504         mutable ExeName m_exeName;
9505         std::vector<Opt> m_options;
9506         std::vector<Arg> m_args;
9507 
operator |=Catch::clara::detail::Parser9508         auto operator|=( ExeName const &exeName ) -> Parser & {
9509             m_exeName = exeName;
9510             return *this;
9511         }
9512 
operator |=Catch::clara::detail::Parser9513         auto operator|=( Arg const &arg ) -> Parser & {
9514             m_args.push_back(arg);
9515             return *this;
9516         }
9517 
operator |=Catch::clara::detail::Parser9518         auto operator|=( Opt const &opt ) -> Parser & {
9519             m_options.push_back(opt);
9520             return *this;
9521         }
9522 
operator |=Catch::clara::detail::Parser9523         auto operator|=( Parser const &other ) -> Parser & {
9524             m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9525             m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9526             return *this;
9527         }
9528 
9529         template<typename T>
operator |Catch::clara::detail::Parser9530         auto operator|( T const &other ) const -> Parser {
9531             return Parser( *this ) |= other;
9532         }
9533 
9534         // Forward deprecated interface with '+' instead of '|'
9535         template<typename T>
operator +=Catch::clara::detail::Parser9536         auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9537         template<typename T>
operator +Catch::clara::detail::Parser9538         auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9539 
getHelpColumnsCatch::clara::detail::Parser9540         auto getHelpColumns() const -> std::vector<HelpColumns> {
9541             std::vector<HelpColumns> cols;
9542             for (auto const &o : m_options) {
9543                 auto childCols = o.getHelpColumns();
9544                 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9545             }
9546             return cols;
9547         }
9548 
writeToStreamCatch::clara::detail::Parser9549         void writeToStream( std::ostream &os ) const {
9550             if (!m_exeName.name().empty()) {
9551                 os << "usage:\n" << "  " << m_exeName.name() << " ";
9552                 bool required = true, first = true;
9553                 for( auto const &arg : m_args ) {
9554                     if (first)
9555                         first = false;
9556                     else
9557                         os << " ";
9558                     if( arg.isOptional() && required ) {
9559                         os << "[";
9560                         required = false;
9561                     }
9562                     os << "<" << arg.hint() << ">";
9563                     if( arg.cardinality() == 0 )
9564                         os << " ... ";
9565                 }
9566                 if( !required )
9567                     os << "]";
9568                 if( !m_options.empty() )
9569                     os << " options";
9570                 os << "\n\nwhere options are:" << std::endl;
9571             }
9572 
9573             auto rows = getHelpColumns();
9574             size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9575             size_t optWidth = 0;
9576             for( auto const &cols : rows )
9577                 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9578 
9579             optWidth = (std::min)(optWidth, consoleWidth/2);
9580 
9581             for( auto const &cols : rows ) {
9582                 auto row =
9583                         TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9584                         TextFlow::Spacer(4) +
9585                         TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9586                 os << row << std::endl;
9587             }
9588         }
9589 
operator <<(std::ostream & os,Parser const & parser)9590         friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9591             parser.writeToStream( os );
9592             return os;
9593         }
9594 
validateCatch::clara::detail::Parser9595         auto validate() const -> Result override {
9596             for( auto const &opt : m_options ) {
9597                 auto result = opt.validate();
9598                 if( !result )
9599                     return result;
9600             }
9601             for( auto const &arg : m_args ) {
9602                 auto result = arg.validate();
9603                 if( !result )
9604                     return result;
9605             }
9606             return Result::ok();
9607         }
9608 
9609         using ParserBase::parse;
9610 
parseCatch::clara::detail::Parser9611         auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9612 
9613             struct ParserInfo {
9614                 ParserBase const* parser = nullptr;
9615                 size_t count = 0;
9616             };
9617             const size_t totalParsers = m_options.size() + m_args.size();
9618             assert( totalParsers < 512 );
9619             // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9620             ParserInfo parseInfos[512];
9621 
9622             {
9623                 size_t i = 0;
9624                 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9625                 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9626             }
9627 
9628             m_exeName.set( exeName );
9629 
9630             auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9631             while( result.value().remainingTokens() ) {
9632                 bool tokenParsed = false;
9633 
9634                 for( size_t i = 0; i < totalParsers; ++i ) {
9635                     auto&  parseInfo = parseInfos[i];
9636                     if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9637                         result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9638                         if (!result)
9639                             return result;
9640                         if (result.value().type() != ParseResultType::NoMatch) {
9641                             tokenParsed = true;
9642                             ++parseInfo.count;
9643                             break;
9644                         }
9645                     }
9646                 }
9647 
9648                 if( result.value().type() == ParseResultType::ShortCircuitAll )
9649                     return result;
9650                 if( !tokenParsed )
9651                     return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9652             }
9653             // !TBD Check missing required options
9654             return result;
9655         }
9656     };
9657 
9658     template<typename DerivedT>
9659     template<typename T>
operator |(T const & other) const9660     auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9661         return Parser() | static_cast<DerivedT const &>( *this ) | other;
9662     }
9663 } // namespace detail
9664 
9665 // A Combined parser
9666 using detail::Parser;
9667 
9668 // A parser for options
9669 using detail::Opt;
9670 
9671 // A parser for arguments
9672 using detail::Arg;
9673 
9674 // Wrapper for argc, argv from main()
9675 using detail::Args;
9676 
9677 // Specifies the name of the executable
9678 using detail::ExeName;
9679 
9680 // Convenience wrapper for option parser that specifies the help option
9681 using detail::Help;
9682 
9683 // enum of result types from a parse
9684 using detail::ParseResultType;
9685 
9686 // Result type for parser operation
9687 using detail::ParserResult;
9688 
9689 }} // namespace Catch::clara
9690 
9691 // end clara.hpp
9692 #ifdef __clang__
9693 #pragma clang diagnostic pop
9694 #endif
9695 
9696 // Restore Clara's value for console width, if present
9697 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9698 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9699 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9700 #endif
9701 
9702 // end catch_clara.h
9703 namespace Catch {
9704 
9705     clara::Parser makeCommandLineParser( ConfigData& config );
9706 
9707 } // end namespace Catch
9708 
9709 // end catch_commandline.h
9710 #include <fstream>
9711 #include <ctime>
9712 
9713 namespace Catch {
9714 
makeCommandLineParser(ConfigData & config)9715     clara::Parser makeCommandLineParser( ConfigData& config ) {
9716 
9717         using namespace clara;
9718 
9719         auto const setWarning = [&]( std::string const& warning ) {
9720                 auto warningSet = [&]() {
9721                     if( warning == "NoAssertions" )
9722                         return WarnAbout::NoAssertions;
9723 
9724                     if ( warning == "NoTests" )
9725                         return WarnAbout::NoTests;
9726 
9727                     return WarnAbout::Nothing;
9728                 }();
9729 
9730                 if (warningSet == WarnAbout::Nothing)
9731                     return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9732                 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9733                 return ParserResult::ok( ParseResultType::Matched );
9734             };
9735         auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9736                 std::ifstream f( filename.c_str() );
9737                 if( !f.is_open() )
9738                     return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9739 
9740                 std::string line;
9741                 while( std::getline( f, line ) ) {
9742                     line = trim(line);
9743                     if( !line.empty() && !startsWith( line, '#' ) ) {
9744                         if( !startsWith( line, '"' ) )
9745                             line = '"' + line + '"';
9746                         config.testsOrTags.push_back( line );
9747                         config.testsOrTags.emplace_back( "," );
9748                     }
9749                 }
9750                 //Remove comma in the end
9751                 if(!config.testsOrTags.empty())
9752                     config.testsOrTags.erase( config.testsOrTags.end()-1 );
9753 
9754                 return ParserResult::ok( ParseResultType::Matched );
9755             };
9756         auto const setTestOrder = [&]( std::string const& order ) {
9757                 if( startsWith( "declared", order ) )
9758                     config.runOrder = RunTests::InDeclarationOrder;
9759                 else if( startsWith( "lexical", order ) )
9760                     config.runOrder = RunTests::InLexicographicalOrder;
9761                 else if( startsWith( "random", order ) )
9762                     config.runOrder = RunTests::InRandomOrder;
9763                 else
9764                     return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9765                 return ParserResult::ok( ParseResultType::Matched );
9766             };
9767         auto const setRngSeed = [&]( std::string const& seed ) {
9768                 if( seed != "time" )
9769                     return clara::detail::convertInto( seed, config.rngSeed );
9770                 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9771                 return ParserResult::ok( ParseResultType::Matched );
9772             };
9773         auto const setColourUsage = [&]( std::string const& useColour ) {
9774                     auto mode = toLower( useColour );
9775 
9776                     if( mode == "yes" )
9777                         config.useColour = UseColour::Yes;
9778                     else if( mode == "no" )
9779                         config.useColour = UseColour::No;
9780                     else if( mode == "auto" )
9781                         config.useColour = UseColour::Auto;
9782                     else
9783                         return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9784                 return ParserResult::ok( ParseResultType::Matched );
9785             };
9786         auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9787                 auto keypressLc = toLower( keypress );
9788                 if (keypressLc == "never")
9789                     config.waitForKeypress = WaitForKeypress::Never;
9790                 else if( keypressLc == "start" )
9791                     config.waitForKeypress = WaitForKeypress::BeforeStart;
9792                 else if( keypressLc == "exit" )
9793                     config.waitForKeypress = WaitForKeypress::BeforeExit;
9794                 else if( keypressLc == "both" )
9795                     config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9796                 else
9797                     return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
9798             return ParserResult::ok( ParseResultType::Matched );
9799             };
9800         auto const setVerbosity = [&]( std::string const& verbosity ) {
9801             auto lcVerbosity = toLower( verbosity );
9802             if( lcVerbosity == "quiet" )
9803                 config.verbosity = Verbosity::Quiet;
9804             else if( lcVerbosity == "normal" )
9805                 config.verbosity = Verbosity::Normal;
9806             else if( lcVerbosity == "high" )
9807                 config.verbosity = Verbosity::High;
9808             else
9809                 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9810             return ParserResult::ok( ParseResultType::Matched );
9811         };
9812         auto const setReporter = [&]( std::string const& reporter ) {
9813             IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9814 
9815             auto lcReporter = toLower( reporter );
9816             auto result = factories.find( lcReporter );
9817 
9818             if( factories.end() != result )
9819                 config.reporterName = lcReporter;
9820             else
9821                 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9822             return ParserResult::ok( ParseResultType::Matched );
9823         };
9824 
9825         auto cli
9826             = ExeName( config.processName )
9827             | Help( config.showHelp )
9828             | Opt( config.listTests )
9829                 ["-l"]["--list-tests"]
9830                 ( "list all/matching test cases" )
9831             | Opt( config.listTags )
9832                 ["-t"]["--list-tags"]
9833                 ( "list all/matching tags" )
9834             | Opt( config.showSuccessfulTests )
9835                 ["-s"]["--success"]
9836                 ( "include successful tests in output" )
9837             | Opt( config.shouldDebugBreak )
9838                 ["-b"]["--break"]
9839                 ( "break into debugger on failure" )
9840             | Opt( config.noThrow )
9841                 ["-e"]["--nothrow"]
9842                 ( "skip exception tests" )
9843             | Opt( config.showInvisibles )
9844                 ["-i"]["--invisibles"]
9845                 ( "show invisibles (tabs, newlines)" )
9846             | Opt( config.outputFilename, "filename" )
9847                 ["-o"]["--out"]
9848                 ( "output filename" )
9849             | Opt( setReporter, "name" )
9850                 ["-r"]["--reporter"]
9851                 ( "reporter to use (defaults to console)" )
9852             | Opt( config.name, "name" )
9853                 ["-n"]["--name"]
9854                 ( "suite name" )
9855             | Opt( [&]( bool ){ config.abortAfter = 1; } )
9856                 ["-a"]["--abort"]
9857                 ( "abort at first failure" )
9858             | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9859                 ["-x"]["--abortx"]
9860                 ( "abort after x failures" )
9861             | Opt( setWarning, "warning name" )
9862                 ["-w"]["--warn"]
9863                 ( "enable warnings" )
9864             | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9865                 ["-d"]["--durations"]
9866                 ( "show test durations" )
9867             | Opt( config.minDuration, "seconds" )
9868                 ["-D"]["--min-duration"]
9869                 ( "show test durations for tests taking at least the given number of seconds" )
9870             | Opt( loadTestNamesFromFile, "filename" )
9871                 ["-f"]["--input-file"]
9872                 ( "load test names to run from a file" )
9873             | Opt( config.filenamesAsTags )
9874                 ["-#"]["--filenames-as-tags"]
9875                 ( "adds a tag for the filename" )
9876             | Opt( config.sectionsToRun, "section name" )
9877                 ["-c"]["--section"]
9878                 ( "specify section to run" )
9879             | Opt( setVerbosity, "quiet|normal|high" )
9880                 ["-v"]["--verbosity"]
9881                 ( "set output verbosity" )
9882             | Opt( config.listTestNamesOnly )
9883                 ["--list-test-names-only"]
9884                 ( "list all/matching test cases names only" )
9885             | Opt( config.listReporters )
9886                 ["--list-reporters"]
9887                 ( "list all reporters" )
9888             | Opt( setTestOrder, "decl|lex|rand" )
9889                 ["--order"]
9890                 ( "test case order (defaults to decl)" )
9891             | Opt( setRngSeed, "'time'|number" )
9892                 ["--rng-seed"]
9893                 ( "set a specific seed for random numbers" )
9894             | Opt( setColourUsage, "yes|no" )
9895                 ["--use-colour"]
9896                 ( "should output be colourised" )
9897             | Opt( config.libIdentify )
9898                 ["--libidentify"]
9899                 ( "report name and version according to libidentify standard" )
9900             | Opt( setWaitForKeypress, "never|start|exit|both" )
9901                 ["--wait-for-keypress"]
9902                 ( "waits for a keypress before exiting" )
9903             | Opt( config.benchmarkSamples, "samples" )
9904                 ["--benchmark-samples"]
9905                 ( "number of samples to collect (default: 100)" )
9906             | Opt( config.benchmarkResamples, "resamples" )
9907                 ["--benchmark-resamples"]
9908                 ( "number of resamples for the bootstrap (default: 100000)" )
9909             | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9910                 ["--benchmark-confidence-interval"]
9911                 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9912             | Opt( config.benchmarkNoAnalysis )
9913                 ["--benchmark-no-analysis"]
9914                 ( "perform only measurements; do not perform any analysis" )
9915             | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
9916                 ["--benchmark-warmup-time"]
9917                 ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
9918             | Arg( config.testsOrTags, "test name|pattern|tags" )
9919                 ( "which test or tests to use" );
9920 
9921         return cli;
9922     }
9923 
9924 } // end namespace Catch
9925 // end catch_commandline.cpp
9926 // start catch_common.cpp
9927 
9928 #include <cstring>
9929 #include <ostream>
9930 
9931 namespace Catch {
9932 
operator ==(SourceLineInfo const & other) const9933     bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9934         return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9935     }
operator <(SourceLineInfo const & other) const9936     bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9937         // We can assume that the same file will usually have the same pointer.
9938         // Thus, if the pointers are the same, there is no point in calling the strcmp
9939         return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9940     }
9941 
operator <<(std::ostream & os,SourceLineInfo const & info)9942     std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9943 #ifndef __GNUG__
9944         os << info.file << '(' << info.line << ')';
9945 #else
9946         os << info.file << ':' << info.line;
9947 #endif
9948         return os;
9949     }
9950 
operator +() const9951     std::string StreamEndStop::operator+() const {
9952         return std::string();
9953     }
9954 
9955     NonCopyable::NonCopyable() = default;
9956     NonCopyable::~NonCopyable() = default;
9957 
9958 }
9959 // end catch_common.cpp
9960 // start catch_config.cpp
9961 
9962 namespace Catch {
9963 
Config(ConfigData const & data)9964     Config::Config( ConfigData const& data )
9965     :   m_data( data ),
9966         m_stream( openStream() )
9967     {
9968         // We need to trim filter specs to avoid trouble with superfluous
9969         // whitespace (esp. important for bdd macros, as those are manually
9970         // aligned with whitespace).
9971 
9972         for (auto& elem : m_data.testsOrTags) {
9973             elem = trim(elem);
9974         }
9975         for (auto& elem : m_data.sectionsToRun) {
9976             elem = trim(elem);
9977         }
9978 
9979         TestSpecParser parser(ITagAliasRegistry::get());
9980         if (!m_data.testsOrTags.empty()) {
9981             m_hasTestFilters = true;
9982             for (auto const& testOrTags : m_data.testsOrTags) {
9983                 parser.parse(testOrTags);
9984             }
9985         }
9986         m_testSpec = parser.testSpec();
9987     }
9988 
getFilename() const9989     std::string const& Config::getFilename() const {
9990         return m_data.outputFilename ;
9991     }
9992 
listTests() const9993     bool Config::listTests() const          { return m_data.listTests; }
listTestNamesOnly() const9994     bool Config::listTestNamesOnly() const  { return m_data.listTestNamesOnly; }
listTags() const9995     bool Config::listTags() const           { return m_data.listTags; }
listReporters() const9996     bool Config::listReporters() const      { return m_data.listReporters; }
9997 
getProcessName() const9998     std::string Config::getProcessName() const { return m_data.processName; }
getReporterName() const9999     std::string const& Config::getReporterName() const { return m_data.reporterName; }
10000 
getTestsOrTags() const10001     std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
getSectionsToRun() const10002     std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
10003 
testSpec() const10004     TestSpec const& Config::testSpec() const { return m_testSpec; }
hasTestFilters() const10005     bool Config::hasTestFilters() const { return m_hasTestFilters; }
10006 
showHelp() const10007     bool Config::showHelp() const { return m_data.showHelp; }
10008 
10009     // IConfig interface
allowThrows() const10010     bool Config::allowThrows() const                   { return !m_data.noThrow; }
stream() const10011     std::ostream& Config::stream() const               { return m_stream->stream(); }
name() const10012     std::string Config::name() const                   { return m_data.name.empty() ? m_data.processName : m_data.name; }
includeSuccessfulResults() const10013     bool Config::includeSuccessfulResults() const      { return m_data.showSuccessfulTests; }
warnAboutMissingAssertions() const10014     bool Config::warnAboutMissingAssertions() const    { return !!(m_data.warnings & WarnAbout::NoAssertions); }
warnAboutNoTests() const10015     bool Config::warnAboutNoTests() const              { return !!(m_data.warnings & WarnAbout::NoTests); }
showDurations() const10016     ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
minDuration() const10017     double Config::minDuration() const                 { return m_data.minDuration; }
runOrder() const10018     RunTests::InWhatOrder Config::runOrder() const     { return m_data.runOrder; }
rngSeed() const10019     unsigned int Config::rngSeed() const               { return m_data.rngSeed; }
useColour() const10020     UseColour::YesOrNo Config::useColour() const       { return m_data.useColour; }
shouldDebugBreak() const10021     bool Config::shouldDebugBreak() const              { return m_data.shouldDebugBreak; }
abortAfter() const10022     int Config::abortAfter() const                     { return m_data.abortAfter; }
showInvisibles() const10023     bool Config::showInvisibles() const                { return m_data.showInvisibles; }
verbosity() const10024     Verbosity Config::verbosity() const                { return m_data.verbosity; }
10025 
benchmarkNoAnalysis() const10026     bool Config::benchmarkNoAnalysis() const                      { return m_data.benchmarkNoAnalysis; }
benchmarkSamples() const10027     int Config::benchmarkSamples() const                          { return m_data.benchmarkSamples; }
benchmarkConfidenceInterval() const10028     double Config::benchmarkConfidenceInterval() const            { return m_data.benchmarkConfidenceInterval; }
benchmarkResamples() const10029     unsigned int Config::benchmarkResamples() const               { return m_data.benchmarkResamples; }
benchmarkWarmupTime() const10030     std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10031 
openStream()10032     IStream const* Config::openStream() {
10033         return Catch::makeStream(m_data.outputFilename);
10034     }
10035 
10036 } // end namespace Catch
10037 // end catch_config.cpp
10038 // start catch_console_colour.cpp
10039 
10040 #if defined(__clang__)
10041 #    pragma clang diagnostic push
10042 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
10043 #endif
10044 
10045 // start catch_errno_guard.h
10046 
10047 namespace Catch {
10048 
10049     class ErrnoGuard {
10050     public:
10051         ErrnoGuard();
10052         ~ErrnoGuard();
10053     private:
10054         int m_oldErrno;
10055     };
10056 
10057 }
10058 
10059 // end catch_errno_guard.h
10060 #include <sstream>
10061 
10062 namespace Catch {
10063     namespace {
10064 
10065         struct IColourImpl {
10066             virtual ~IColourImpl() = default;
10067             virtual void use( Colour::Code _colourCode ) = 0;
10068         };
10069 
10070         struct NoColourImpl : IColourImpl {
useCatch::__anon08ec97e12d11::NoColourImpl10071             void use( Colour::Code ) override {}
10072 
instanceCatch::__anon08ec97e12d11::NoColourImpl10073             static IColourImpl* instance() {
10074                 static NoColourImpl s_instance;
10075                 return &s_instance;
10076             }
10077         };
10078 
10079     } // anon namespace
10080 } // namespace Catch
10081 
10082 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10083 #   ifdef CATCH_PLATFORM_WINDOWS
10084 #       define CATCH_CONFIG_COLOUR_WINDOWS
10085 #   else
10086 #       define CATCH_CONFIG_COLOUR_ANSI
10087 #   endif
10088 #endif
10089 
10090 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
10091 
10092 namespace Catch {
10093 namespace {
10094 
10095     class Win32ColourImpl : public IColourImpl {
10096     public:
Win32ColourImpl()10097         Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10098         {
10099             CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10100             GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10101             originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10102             originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10103         }
10104 
use(Colour::Code _colourCode)10105         void use( Colour::Code _colourCode ) override {
10106             switch( _colourCode ) {
10107                 case Colour::None:      return setTextAttribute( originalForegroundAttributes );
10108                 case Colour::White:     return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10109                 case Colour::Red:       return setTextAttribute( FOREGROUND_RED );
10110                 case Colour::Green:     return setTextAttribute( FOREGROUND_GREEN );
10111                 case Colour::Blue:      return setTextAttribute( FOREGROUND_BLUE );
10112                 case Colour::Cyan:      return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10113                 case Colour::Yellow:    return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10114                 case Colour::Grey:      return setTextAttribute( 0 );
10115 
10116                 case Colour::LightGrey:     return setTextAttribute( FOREGROUND_INTENSITY );
10117                 case Colour::BrightRed:     return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10118                 case Colour::BrightGreen:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10119                 case Colour::BrightWhite:   return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10120                 case Colour::BrightYellow:  return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10121 
10122                 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10123 
10124                 default:
10125                     CATCH_ERROR( "Unknown colour requested" );
10126             }
10127         }
10128 
10129     private:
setTextAttribute(WORD _textAttribute)10130         void setTextAttribute( WORD _textAttribute ) {
10131             SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10132         }
10133         HANDLE stdoutHandle;
10134         WORD originalForegroundAttributes;
10135         WORD originalBackgroundAttributes;
10136     };
10137 
platformColourInstance()10138     IColourImpl* platformColourInstance() {
10139         static Win32ColourImpl s_instance;
10140 
10141         IConfigPtr config = getCurrentContext().getConfig();
10142         UseColour::YesOrNo colourMode = config
10143             ? config->useColour()
10144             : UseColour::Auto;
10145         if( colourMode == UseColour::Auto )
10146             colourMode = UseColour::Yes;
10147         return colourMode == UseColour::Yes
10148             ? &s_instance
10149             : NoColourImpl::instance();
10150     }
10151 
10152 } // end anon namespace
10153 } // end namespace Catch
10154 
10155 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
10156 
10157 #include <unistd.h>
10158 
10159 namespace Catch {
10160 namespace {
10161 
10162     // use POSIX/ ANSI console terminal codes
10163     // Thanks to Adam Strzelecki for original contribution
10164     // (http://github.com/nanoant)
10165     // https://github.com/philsquared/Catch/pull/131
10166     class PosixColourImpl : public IColourImpl {
10167     public:
use(Colour::Code _colourCode)10168         void use( Colour::Code _colourCode ) override {
10169             switch( _colourCode ) {
10170                 case Colour::None:
10171                 case Colour::White:     return setColour( "[0m" );
10172                 case Colour::Red:       return setColour( "[0;31m" );
10173                 case Colour::Green:     return setColour( "[0;32m" );
10174                 case Colour::Blue:      return setColour( "[0;34m" );
10175                 case Colour::Cyan:      return setColour( "[0;36m" );
10176                 case Colour::Yellow:    return setColour( "[0;33m" );
10177                 case Colour::Grey:      return setColour( "[1;30m" );
10178 
10179                 case Colour::LightGrey:     return setColour( "[0;37m" );
10180                 case Colour::BrightRed:     return setColour( "[1;31m" );
10181                 case Colour::BrightGreen:   return setColour( "[1;32m" );
10182                 case Colour::BrightWhite:   return setColour( "[1;37m" );
10183                 case Colour::BrightYellow:  return setColour( "[1;33m" );
10184 
10185                 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10186                 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
10187             }
10188         }
instance()10189         static IColourImpl* instance() {
10190             static PosixColourImpl s_instance;
10191             return &s_instance;
10192         }
10193 
10194     private:
setColour(const char * _escapeCode)10195         void setColour( const char* _escapeCode ) {
10196             getCurrentContext().getConfig()->stream()
10197                 << '\033' << _escapeCode;
10198         }
10199     };
10200 
useColourOnPlatform()10201     bool useColourOnPlatform() {
10202         return
10203 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10204             !isDebuggerActive() &&
10205 #endif
10206 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10207             isatty(STDOUT_FILENO)
10208 #else
10209             false
10210 #endif
10211             ;
10212     }
platformColourInstance()10213     IColourImpl* platformColourInstance() {
10214         ErrnoGuard guard;
10215         IConfigPtr config = getCurrentContext().getConfig();
10216         UseColour::YesOrNo colourMode = config
10217             ? config->useColour()
10218             : UseColour::Auto;
10219         if( colourMode == UseColour::Auto )
10220             colourMode = useColourOnPlatform()
10221                 ? UseColour::Yes
10222                 : UseColour::No;
10223         return colourMode == UseColour::Yes
10224             ? PosixColourImpl::instance()
10225             : NoColourImpl::instance();
10226     }
10227 
10228 } // end anon namespace
10229 } // end namespace Catch
10230 
10231 #else  // not Windows or ANSI ///////////////////////////////////////////////
10232 
10233 namespace Catch {
10234 
platformColourInstance()10235     static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10236 
10237 } // end namespace Catch
10238 
10239 #endif // Windows/ ANSI/ None
10240 
10241 namespace Catch {
10242 
Colour(Code _colourCode)10243     Colour::Colour( Code _colourCode ) { use( _colourCode ); }
Colour(Colour && other)10244     Colour::Colour( Colour&& other ) noexcept {
10245         m_moved = other.m_moved;
10246         other.m_moved = true;
10247     }
operator =(Colour && other)10248     Colour& Colour::operator=( Colour&& other ) noexcept {
10249         m_moved = other.m_moved;
10250         other.m_moved  = true;
10251         return *this;
10252     }
10253 
~Colour()10254     Colour::~Colour(){ if( !m_moved ) use( None ); }
10255 
use(Code _colourCode)10256     void Colour::use( Code _colourCode ) {
10257         static IColourImpl* impl = platformColourInstance();
10258         // Strictly speaking, this cannot possibly happen.
10259         // However, under some conditions it does happen (see #1626),
10260         // and this change is small enough that we can let practicality
10261         // triumph over purity in this case.
10262         if (impl != nullptr) {
10263             impl->use( _colourCode );
10264         }
10265     }
10266 
operator <<(std::ostream & os,Colour const &)10267     std::ostream& operator << ( std::ostream& os, Colour const& ) {
10268         return os;
10269     }
10270 
10271 } // end namespace Catch
10272 
10273 #if defined(__clang__)
10274 #    pragma clang diagnostic pop
10275 #endif
10276 
10277 // end catch_console_colour.cpp
10278 // start catch_context.cpp
10279 
10280 namespace Catch {
10281 
10282     class Context : public IMutableContext, NonCopyable {
10283 
10284     public: // IContext
getResultCapture()10285         IResultCapture* getResultCapture() override {
10286             return m_resultCapture;
10287         }
getRunner()10288         IRunner* getRunner() override {
10289             return m_runner;
10290         }
10291 
getConfig() const10292         IConfigPtr const& getConfig() const override {
10293             return m_config;
10294         }
10295 
10296         ~Context() override;
10297 
10298     public: // IMutableContext
setResultCapture(IResultCapture * resultCapture)10299         void setResultCapture( IResultCapture* resultCapture ) override {
10300             m_resultCapture = resultCapture;
10301         }
setRunner(IRunner * runner)10302         void setRunner( IRunner* runner ) override {
10303             m_runner = runner;
10304         }
setConfig(IConfigPtr const & config)10305         void setConfig( IConfigPtr const& config ) override {
10306             m_config = config;
10307         }
10308 
10309         friend IMutableContext& getCurrentMutableContext();
10310 
10311     private:
10312         IConfigPtr m_config;
10313         IRunner* m_runner = nullptr;
10314         IResultCapture* m_resultCapture = nullptr;
10315     };
10316 
10317     IMutableContext *IMutableContext::currentContext = nullptr;
10318 
createContext()10319     void IMutableContext::createContext()
10320     {
10321         currentContext = new Context();
10322     }
10323 
cleanUpContext()10324     void cleanUpContext() {
10325         delete IMutableContext::currentContext;
10326         IMutableContext::currentContext = nullptr;
10327     }
10328     IContext::~IContext() = default;
10329     IMutableContext::~IMutableContext() = default;
10330     Context::~Context() = default;
10331 
rng()10332     SimplePcg32& rng() {
10333         static SimplePcg32 s_rng;
10334         return s_rng;
10335     }
10336 
10337 }
10338 // end catch_context.cpp
10339 // start catch_debug_console.cpp
10340 
10341 // start catch_debug_console.h
10342 
10343 #include <string>
10344 
10345 namespace Catch {
10346     void writeToDebugConsole( std::string const& text );
10347 }
10348 
10349 // end catch_debug_console.h
10350 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10351 #include <android/log.h>
10352 
10353     namespace Catch {
writeToDebugConsole(std::string const & text)10354         void writeToDebugConsole( std::string const& text ) {
10355             __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
10356         }
10357     }
10358 
10359 #elif defined(CATCH_PLATFORM_WINDOWS)
10360 
10361     namespace Catch {
writeToDebugConsole(std::string const & text)10362         void writeToDebugConsole( std::string const& text ) {
10363             ::OutputDebugStringA( text.c_str() );
10364         }
10365     }
10366 
10367 #else
10368 
10369     namespace Catch {
writeToDebugConsole(std::string const & text)10370         void writeToDebugConsole( std::string const& text ) {
10371             // !TBD: Need a version for Mac/ XCode and other IDEs
10372             Catch::cout() << text;
10373         }
10374     }
10375 
10376 #endif // Platform
10377 // end catch_debug_console.cpp
10378 // start catch_debugger.cpp
10379 
10380 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10381 
10382 #  include <cassert>
10383 #  include <sys/types.h>
10384 #  include <unistd.h>
10385 #  include <cstddef>
10386 #  include <ostream>
10387 
10388 #ifdef __apple_build_version__
10389     // These headers will only compile with AppleClang (XCode)
10390     // For other compilers (Clang, GCC, ... ) we need to exclude them
10391 #  include <sys/sysctl.h>
10392 #endif
10393 
10394     namespace Catch {
10395         #ifdef __apple_build_version__
10396         // The following function is taken directly from the following technical note:
10397         // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10398 
10399         // Returns true if the current process is being debugged (either
10400         // running under the debugger or has a debugger attached post facto).
isDebuggerActive()10401         bool isDebuggerActive(){
10402             int                 mib[4];
10403             struct kinfo_proc   info;
10404             std::size_t         size;
10405 
10406             // Initialize the flags so that, if sysctl fails for some bizarre
10407             // reason, we get a predictable result.
10408 
10409             info.kp_proc.p_flag = 0;
10410 
10411             // Initialize mib, which tells sysctl the info we want, in this case
10412             // we're looking for information about a specific process ID.
10413 
10414             mib[0] = CTL_KERN;
10415             mib[1] = KERN_PROC;
10416             mib[2] = KERN_PROC_PID;
10417             mib[3] = getpid();
10418 
10419             // Call sysctl.
10420 
10421             size = sizeof(info);
10422             if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10423                 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10424                 return false;
10425             }
10426 
10427             // We're being debugged if the P_TRACED flag is set.
10428 
10429             return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10430         }
10431         #else
10432         bool isDebuggerActive() {
10433             // We need to find another way to determine this for non-appleclang compilers on macOS
10434             return false;
10435         }
10436         #endif
10437     } // namespace Catch
10438 
10439 #elif defined(CATCH_PLATFORM_LINUX)
10440     #include <fstream>
10441     #include <string>
10442 
10443     namespace Catch{
10444         // The standard POSIX way of detecting a debugger is to attempt to
10445         // ptrace() the process, but this needs to be done from a child and not
10446         // this process itself to still allow attaching to this process later
10447         // if wanted, so is rather heavy. Under Linux we have the PID of the
10448         // "debugger" (which doesn't need to be gdb, of course, it could also
10449         // be strace, for example) in /proc/$PID/status, so just get it from
10450         // there instead.
isDebuggerActive()10451         bool isDebuggerActive(){
10452             // Libstdc++ has a bug, where std::ifstream sets errno to 0
10453             // This way our users can properly assert over errno values
10454             ErrnoGuard guard;
10455             std::ifstream in("/proc/self/status");
10456             for( std::string line; std::getline(in, line); ) {
10457                 static const int PREFIX_LEN = 11;
10458                 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10459                     // We're traced if the PID is not 0 and no other PID starts
10460                     // with 0 digit, so it's enough to check for just a single
10461                     // character.
10462                     return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10463                 }
10464             }
10465 
10466             return false;
10467         }
10468     } // namespace Catch
10469 #elif defined(_MSC_VER)
10470     extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10471     namespace Catch {
isDebuggerActive()10472         bool isDebuggerActive() {
10473             return IsDebuggerPresent() != 0;
10474         }
10475     }
10476 #elif defined(__MINGW32__)
10477     extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10478     namespace Catch {
isDebuggerActive()10479         bool isDebuggerActive() {
10480             return IsDebuggerPresent() != 0;
10481         }
10482     }
10483 #else
10484     namespace Catch {
isDebuggerActive()10485        bool isDebuggerActive() { return false; }
10486     }
10487 #endif // Platform
10488 // end catch_debugger.cpp
10489 // start catch_decomposer.cpp
10490 
10491 namespace Catch {
10492 
10493     ITransientExpression::~ITransientExpression() = default;
10494 
formatReconstructedExpression(std::ostream & os,std::string const & lhs,StringRef op,std::string const & rhs)10495     void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10496         if( lhs.size() + rhs.size() < 40 &&
10497                 lhs.find('\n') == std::string::npos &&
10498                 rhs.find('\n') == std::string::npos )
10499             os << lhs << " " << op << " " << rhs;
10500         else
10501             os << lhs << "\n" << op << "\n" << rhs;
10502     }
10503 }
10504 // end catch_decomposer.cpp
10505 // start catch_enforce.cpp
10506 
10507 #include <stdexcept>
10508 
10509 namespace Catch {
10510 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10511     [[noreturn]]
throw_exception(std::exception const & e)10512     void throw_exception(std::exception const& e) {
10513         Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10514                       << "The message was: " << e.what() << '\n';
10515         std::terminate();
10516     }
10517 #endif
10518 
10519     [[noreturn]]
throw_logic_error(std::string const & msg)10520     void throw_logic_error(std::string const& msg) {
10521         throw_exception(std::logic_error(msg));
10522     }
10523 
10524     [[noreturn]]
throw_domain_error(std::string const & msg)10525     void throw_domain_error(std::string const& msg) {
10526         throw_exception(std::domain_error(msg));
10527     }
10528 
10529     [[noreturn]]
throw_runtime_error(std::string const & msg)10530     void throw_runtime_error(std::string const& msg) {
10531         throw_exception(std::runtime_error(msg));
10532     }
10533 
10534 } // namespace Catch;
10535 // end catch_enforce.cpp
10536 // start catch_enum_values_registry.cpp
10537 // start catch_enum_values_registry.h
10538 
10539 #include <vector>
10540 #include <memory>
10541 
10542 namespace Catch {
10543 
10544     namespace Detail {
10545 
10546         std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10547 
10548         class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10549 
10550             std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10551 
10552             EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10553         };
10554 
10555         std::vector<StringRef> parseEnums( StringRef enums );
10556 
10557     } // Detail
10558 
10559 } // Catch
10560 
10561 // end catch_enum_values_registry.h
10562 
10563 #include <map>
10564 #include <cassert>
10565 
10566 namespace Catch {
10567 
~IMutableEnumValuesRegistry()10568     IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10569 
10570     namespace Detail {
10571 
10572         namespace {
10573             // Extracts the actual name part of an enum instance
10574             // In other words, it returns the Blue part of Bikeshed::Colour::Blue
extractInstanceName(StringRef enumInstance)10575             StringRef extractInstanceName(StringRef enumInstance) {
10576                 // Find last occurence of ":"
10577                 size_t name_start = enumInstance.size();
10578                 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10579                     --name_start;
10580                 }
10581                 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10582             }
10583         }
10584 
parseEnums(StringRef enums)10585         std::vector<StringRef> parseEnums( StringRef enums ) {
10586             auto enumValues = splitStringRef( enums, ',' );
10587             std::vector<StringRef> parsed;
10588             parsed.reserve( enumValues.size() );
10589             for( auto const& enumValue : enumValues ) {
10590                 parsed.push_back(trim(extractInstanceName(enumValue)));
10591             }
10592             return parsed;
10593         }
10594 
~EnumInfo()10595         EnumInfo::~EnumInfo() {}
10596 
lookup(int value) const10597         StringRef EnumInfo::lookup( int value ) const {
10598             for( auto const& valueToName : m_values ) {
10599                 if( valueToName.first == value )
10600                     return valueToName.second;
10601             }
10602             return "{** unexpected enum value **}"_sr;
10603         }
10604 
makeEnumInfo(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10605         std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10606             std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10607             enumInfo->m_name = enumName;
10608             enumInfo->m_values.reserve( values.size() );
10609 
10610             const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10611             assert( valueNames.size() == values.size() );
10612             std::size_t i = 0;
10613             for( auto value : values )
10614                 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10615 
10616             return enumInfo;
10617         }
10618 
registerEnum(StringRef enumName,StringRef allValueNames,std::vector<int> const & values)10619         EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10620             m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10621             return *m_enumInfos.back();
10622         }
10623 
10624     } // Detail
10625 } // Catch
10626 
10627 // end catch_enum_values_registry.cpp
10628 // start catch_errno_guard.cpp
10629 
10630 #include <cerrno>
10631 
10632 namespace Catch {
ErrnoGuard()10633         ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
~ErrnoGuard()10634         ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10635 }
10636 // end catch_errno_guard.cpp
10637 // start catch_exception_translator_registry.cpp
10638 
10639 // start catch_exception_translator_registry.h
10640 
10641 #include <vector>
10642 #include <string>
10643 #include <memory>
10644 
10645 namespace Catch {
10646 
10647     class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10648     public:
10649         ~ExceptionTranslatorRegistry();
10650         virtual void registerTranslator( const IExceptionTranslator* translator );
10651         std::string translateActiveException() const override;
10652         std::string tryTranslators() const;
10653 
10654     private:
10655         std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10656     };
10657 }
10658 
10659 // end catch_exception_translator_registry.h
10660 #ifdef __OBJC__
10661 #import "Foundation/Foundation.h"
10662 #endif
10663 
10664 namespace Catch {
10665 
~ExceptionTranslatorRegistry()10666     ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10667     }
10668 
registerTranslator(const IExceptionTranslator * translator)10669     void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10670         m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10671     }
10672 
10673 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
translateActiveException() const10674     std::string ExceptionTranslatorRegistry::translateActiveException() const {
10675         try {
10676 #ifdef __OBJC__
10677             // In Objective-C try objective-c exceptions first
10678             @try {
10679                 return tryTranslators();
10680             }
10681             @catch (NSException *exception) {
10682                 return Catch::Detail::stringify( [exception description] );
10683             }
10684 #else
10685             // Compiling a mixed mode project with MSVC means that CLR
10686             // exceptions will be caught in (...) as well. However, these
10687             // do not fill-in std::current_exception and thus lead to crash
10688             // when attempting rethrow.
10689             // /EHa switch also causes structured exceptions to be caught
10690             // here, but they fill-in current_exception properly, so
10691             // at worst the output should be a little weird, instead of
10692             // causing a crash.
10693             if (std::current_exception() == nullptr) {
10694                 return "Non C++ exception. Possibly a CLR exception.";
10695             }
10696             return tryTranslators();
10697 #endif
10698         }
10699         catch( TestFailureException& ) {
10700             std::rethrow_exception(std::current_exception());
10701         }
10702         catch( std::exception& ex ) {
10703             return ex.what();
10704         }
10705         catch( std::string& msg ) {
10706             return msg;
10707         }
10708         catch( const char* msg ) {
10709             return msg;
10710         }
10711         catch(...) {
10712             return "Unknown exception";
10713         }
10714     }
10715 
tryTranslators() const10716     std::string ExceptionTranslatorRegistry::tryTranslators() const {
10717         if (m_translators.empty()) {
10718             std::rethrow_exception(std::current_exception());
10719         } else {
10720             return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10721         }
10722     }
10723 
10724 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
translateActiveException() const10725     std::string ExceptionTranslatorRegistry::translateActiveException() const {
10726         CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10727     }
10728 
tryTranslators() const10729     std::string ExceptionTranslatorRegistry::tryTranslators() const {
10730         CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10731     }
10732 #endif
10733 
10734 }
10735 // end catch_exception_translator_registry.cpp
10736 // start catch_fatal_condition.cpp
10737 
10738 #if defined(__GNUC__)
10739 #    pragma GCC diagnostic push
10740 #    pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10741 #endif
10742 
10743 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10744 
10745 namespace {
10746     // Report the error condition
reportFatal(char const * const message)10747     void reportFatal( char const * const message ) {
10748         Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10749     }
10750 }
10751 
10752 #endif // signals/SEH handling
10753 
10754 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10755 
10756 namespace Catch {
10757     struct SignalDefs { DWORD id; const char* name; };
10758 
10759     // There is no 1-1 mapping between signals and windows exceptions.
10760     // Windows can easily distinguish between SO and SigSegV,
10761     // but SigInt, SigTerm, etc are handled differently.
10762     static SignalDefs signalDefs[] = {
10763         { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION),  "SIGILL - Illegal instruction signal" },
10764         { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10765         { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10766         { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10767     };
10768 
handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo)10769     LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10770         for (auto const& def : signalDefs) {
10771             if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10772                 reportFatal(def.name);
10773             }
10774         }
10775         // If its not an exception we care about, pass it along.
10776         // This stops us from eating debugger breaks etc.
10777         return EXCEPTION_CONTINUE_SEARCH;
10778     }
10779 
FatalConditionHandler()10780     FatalConditionHandler::FatalConditionHandler() {
10781         isSet = true;
10782         // 32k seems enough for Catch to handle stack overflow,
10783         // but the value was found experimentally, so there is no strong guarantee
10784         guaranteeSize = 32 * 1024;
10785         exceptionHandlerHandle = nullptr;
10786         // Register as first handler in current chain
10787         exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10788         // Pass in guarantee size to be filled
10789         SetThreadStackGuarantee(&guaranteeSize);
10790     }
10791 
reset()10792     void FatalConditionHandler::reset() {
10793         if (isSet) {
10794             RemoveVectoredExceptionHandler(exceptionHandlerHandle);
10795             SetThreadStackGuarantee(&guaranteeSize);
10796             exceptionHandlerHandle = nullptr;
10797             isSet = false;
10798         }
10799     }
10800 
~FatalConditionHandler()10801     FatalConditionHandler::~FatalConditionHandler() {
10802         reset();
10803     }
10804 
10805 bool FatalConditionHandler::isSet = false;
10806 ULONG FatalConditionHandler::guaranteeSize = 0;
10807 PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
10808 
10809 } // namespace Catch
10810 
10811 #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
10812 
10813 namespace Catch {
10814 
10815     struct SignalDefs {
10816         int id;
10817         const char* name;
10818     };
10819 
10820     // 32kb for the alternate stack seems to be sufficient. However, this value
10821     // is experimentally determined, so that's not guaranteed.
10822     static constexpr std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
10823 
10824     static SignalDefs signalDefs[] = {
10825         { SIGINT,  "SIGINT - Terminal interrupt signal" },
10826         { SIGILL,  "SIGILL - Illegal instruction signal" },
10827         { SIGFPE,  "SIGFPE - Floating point error signal" },
10828         { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10829         { SIGTERM, "SIGTERM - Termination request signal" },
10830         { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10831     };
10832 
handleSignal(int sig)10833     void FatalConditionHandler::handleSignal( int sig ) {
10834         char const * name = "<unknown signal>";
10835         for (auto const& def : signalDefs) {
10836             if (sig == def.id) {
10837                 name = def.name;
10838                 break;
10839             }
10840         }
10841         reset();
10842         reportFatal(name);
10843         raise( sig );
10844     }
10845 
FatalConditionHandler()10846     FatalConditionHandler::FatalConditionHandler() {
10847         isSet = true;
10848         stack_t sigStack;
10849         sigStack.ss_sp = altStackMem;
10850         sigStack.ss_size = sigStackSize;
10851         sigStack.ss_flags = 0;
10852         sigaltstack(&sigStack, &oldSigStack);
10853         struct sigaction sa = { };
10854 
10855         sa.sa_handler = handleSignal;
10856         sa.sa_flags = SA_ONSTACK;
10857         for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10858             sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10859         }
10860     }
10861 
~FatalConditionHandler()10862     FatalConditionHandler::~FatalConditionHandler() {
10863         reset();
10864     }
10865 
reset()10866     void FatalConditionHandler::reset() {
10867         if( isSet ) {
10868             // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
10869             for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
10870                 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10871             }
10872             // Return the old stack
10873             sigaltstack(&oldSigStack, nullptr);
10874             isSet = false;
10875         }
10876     }
10877 
10878     bool FatalConditionHandler::isSet = false;
10879     struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
10880     stack_t FatalConditionHandler::oldSigStack = {};
10881     char FatalConditionHandler::altStackMem[sigStackSize] = {};
10882 
10883 } // namespace Catch
10884 
10885 #else
10886 
10887 namespace Catch {
reset()10888     void FatalConditionHandler::reset() {}
10889 }
10890 
10891 #endif // signals/SEH handling
10892 
10893 #if defined(__GNUC__)
10894 #    pragma GCC diagnostic pop
10895 #endif
10896 // end catch_fatal_condition.cpp
10897 // start catch_generators.cpp
10898 
10899 #include <limits>
10900 #include <set>
10901 
10902 namespace Catch {
10903 
~IGeneratorTracker()10904 IGeneratorTracker::~IGeneratorTracker() {}
10905 
what() const10906 const char* GeneratorException::what() const noexcept {
10907     return m_msg;
10908 }
10909 
10910 namespace Generators {
10911 
~GeneratorUntypedBase()10912     GeneratorUntypedBase::~GeneratorUntypedBase() {}
10913 
acquireGeneratorTracker(StringRef generatorName,SourceLineInfo const & lineInfo)10914     auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10915         return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10916     }
10917 
10918 } // namespace Generators
10919 } // namespace Catch
10920 // end catch_generators.cpp
10921 // start catch_interfaces_capture.cpp
10922 
10923 namespace Catch {
10924     IResultCapture::~IResultCapture() = default;
10925 }
10926 // end catch_interfaces_capture.cpp
10927 // start catch_interfaces_config.cpp
10928 
10929 namespace Catch {
10930     IConfig::~IConfig() = default;
10931 }
10932 // end catch_interfaces_config.cpp
10933 // start catch_interfaces_exception.cpp
10934 
10935 namespace Catch {
10936     IExceptionTranslator::~IExceptionTranslator() = default;
10937     IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
10938 }
10939 // end catch_interfaces_exception.cpp
10940 // start catch_interfaces_registry_hub.cpp
10941 
10942 namespace Catch {
10943     IRegistryHub::~IRegistryHub() = default;
10944     IMutableRegistryHub::~IMutableRegistryHub() = default;
10945 }
10946 // end catch_interfaces_registry_hub.cpp
10947 // start catch_interfaces_reporter.cpp
10948 
10949 // start catch_reporter_listening.h
10950 
10951 namespace Catch {
10952 
10953     class ListeningReporter : public IStreamingReporter {
10954         using Reporters = std::vector<IStreamingReporterPtr>;
10955         Reporters m_listeners;
10956         IStreamingReporterPtr m_reporter = nullptr;
10957         ReporterPreferences m_preferences;
10958 
10959     public:
10960         ListeningReporter();
10961 
10962         void addListener( IStreamingReporterPtr&& listener );
10963         void addReporter( IStreamingReporterPtr&& reporter );
10964 
10965     public: // IStreamingReporter
10966 
10967         ReporterPreferences getPreferences() const override;
10968 
10969         void noMatchingTestCases( std::string const& spec ) override;
10970 
10971         void reportInvalidArguments(std::string const&arg) override;
10972 
10973         static std::set<Verbosity> getSupportedVerbosities();
10974 
10975 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
10976         void benchmarkPreparing(std::string const& name) override;
10977         void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
10978         void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
10979         void benchmarkFailed(std::string const&) override;
10980 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
10981 
10982         void testRunStarting( TestRunInfo const& testRunInfo ) override;
10983         void testGroupStarting( GroupInfo const& groupInfo ) override;
10984         void testCaseStarting( TestCaseInfo const& testInfo ) override;
10985         void sectionStarting( SectionInfo const& sectionInfo ) override;
10986         void assertionStarting( AssertionInfo const& assertionInfo ) override;
10987 
10988         // The return value indicates if the messages buffer should be cleared:
10989         bool assertionEnded( AssertionStats const& assertionStats ) override;
10990         void sectionEnded( SectionStats const& sectionStats ) override;
10991         void testCaseEnded( TestCaseStats const& testCaseStats ) override;
10992         void testGroupEnded( TestGroupStats const& testGroupStats ) override;
10993         void testRunEnded( TestRunStats const& testRunStats ) override;
10994 
10995         void skipTest( TestCaseInfo const& testInfo ) override;
10996         bool isMulti() const override;
10997 
10998     };
10999 
11000 } // end namespace Catch
11001 
11002 // end catch_reporter_listening.h
11003 namespace Catch {
11004 
ReporterConfig(IConfigPtr const & _fullConfig)11005     ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
11006     :   m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11007 
ReporterConfig(IConfigPtr const & _fullConfig,std::ostream & _stream)11008     ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
11009     :   m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11010 
stream() const11011     std::ostream& ReporterConfig::stream() const { return *m_stream; }
fullConfig() const11012     IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11013 
TestRunInfo(std::string const & _name)11014     TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
11015 
GroupInfo(std::string const & _name,std::size_t _groupIndex,std::size_t _groupsCount)11016     GroupInfo::GroupInfo(  std::string const& _name,
11017                            std::size_t _groupIndex,
11018                            std::size_t _groupsCount )
11019     :   name( _name ),
11020         groupIndex( _groupIndex ),
11021         groupsCounts( _groupsCount )
11022     {}
11023 
AssertionStats(AssertionResult const & _assertionResult,std::vector<MessageInfo> const & _infoMessages,Totals const & _totals)11024      AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
11025                                      std::vector<MessageInfo> const& _infoMessages,
11026                                      Totals const& _totals )
11027     :   assertionResult( _assertionResult ),
11028         infoMessages( _infoMessages ),
11029         totals( _totals )
11030     {
11031         assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11032 
11033         if( assertionResult.hasMessage() ) {
11034             // Copy message into messages list.
11035             // !TBD This should have been done earlier, somewhere
11036             MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11037             builder << assertionResult.getMessage();
11038             builder.m_info.message = builder.m_stream.str();
11039 
11040             infoMessages.push_back( builder.m_info );
11041         }
11042     }
11043 
11044      AssertionStats::~AssertionStats() = default;
11045 
SectionStats(SectionInfo const & _sectionInfo,Counts const & _assertions,double _durationInSeconds,bool _missingAssertions)11046     SectionStats::SectionStats(  SectionInfo const& _sectionInfo,
11047                                  Counts const& _assertions,
11048                                  double _durationInSeconds,
11049                                  bool _missingAssertions )
11050     :   sectionInfo( _sectionInfo ),
11051         assertions( _assertions ),
11052         durationInSeconds( _durationInSeconds ),
11053         missingAssertions( _missingAssertions )
11054     {}
11055 
11056     SectionStats::~SectionStats() = default;
11057 
TestCaseStats(TestCaseInfo const & _testInfo,Totals const & _totals,std::string const & _stdOut,std::string const & _stdErr,bool _aborting)11058     TestCaseStats::TestCaseStats(  TestCaseInfo const& _testInfo,
11059                                    Totals const& _totals,
11060                                    std::string const& _stdOut,
11061                                    std::string const& _stdErr,
11062                                    bool _aborting )
11063     : testInfo( _testInfo ),
11064         totals( _totals ),
11065         stdOut( _stdOut ),
11066         stdErr( _stdErr ),
11067         aborting( _aborting )
11068     {}
11069 
11070     TestCaseStats::~TestCaseStats() = default;
11071 
TestGroupStats(GroupInfo const & _groupInfo,Totals const & _totals,bool _aborting)11072     TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
11073                                     Totals const& _totals,
11074                                     bool _aborting )
11075     :   groupInfo( _groupInfo ),
11076         totals( _totals ),
11077         aborting( _aborting )
11078     {}
11079 
TestGroupStats(GroupInfo const & _groupInfo)11080     TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
11081     :   groupInfo( _groupInfo ),
11082         aborting( false )
11083     {}
11084 
11085     TestGroupStats::~TestGroupStats() = default;
11086 
TestRunStats(TestRunInfo const & _runInfo,Totals const & _totals,bool _aborting)11087     TestRunStats::TestRunStats(   TestRunInfo const& _runInfo,
11088                     Totals const& _totals,
11089                     bool _aborting )
11090     :   runInfo( _runInfo ),
11091         totals( _totals ),
11092         aborting( _aborting )
11093     {}
11094 
11095     TestRunStats::~TestRunStats() = default;
11096 
fatalErrorEncountered(StringRef)11097     void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
isMulti() const11098     bool IStreamingReporter::isMulti() const { return false; }
11099 
11100     IReporterFactory::~IReporterFactory() = default;
11101     IReporterRegistry::~IReporterRegistry() = default;
11102 
11103 } // end namespace Catch
11104 // end catch_interfaces_reporter.cpp
11105 // start catch_interfaces_runner.cpp
11106 
11107 namespace Catch {
11108     IRunner::~IRunner() = default;
11109 }
11110 // end catch_interfaces_runner.cpp
11111 // start catch_interfaces_testcase.cpp
11112 
11113 namespace Catch {
11114     ITestInvoker::~ITestInvoker() = default;
11115     ITestCaseRegistry::~ITestCaseRegistry() = default;
11116 }
11117 // end catch_interfaces_testcase.cpp
11118 // start catch_leak_detector.cpp
11119 
11120 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11121 #include <crtdbg.h>
11122 
11123 namespace Catch {
11124 
LeakDetector()11125     LeakDetector::LeakDetector() {
11126         int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11127         flag |= _CRTDBG_LEAK_CHECK_DF;
11128         flag |= _CRTDBG_ALLOC_MEM_DF;
11129         _CrtSetDbgFlag(flag);
11130         _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11131         _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11132         // Change this to leaking allocation's number to break there
11133         _CrtSetBreakAlloc(-1);
11134     }
11135 }
11136 
11137 #else
11138 
LeakDetector()11139     Catch::LeakDetector::LeakDetector() {}
11140 
11141 #endif
11142 
~LeakDetector()11143 Catch::LeakDetector::~LeakDetector() {
11144     Catch::cleanUp();
11145 }
11146 // end catch_leak_detector.cpp
11147 // start catch_list.cpp
11148 
11149 // start catch_list.h
11150 
11151 #include <set>
11152 
11153 namespace Catch {
11154 
11155     std::size_t listTests( Config const& config );
11156 
11157     std::size_t listTestsNamesOnly( Config const& config );
11158 
11159     struct TagInfo {
11160         void add( std::string const& spelling );
11161         std::string all() const;
11162 
11163         std::set<std::string> spellings;
11164         std::size_t count = 0;
11165     };
11166 
11167     std::size_t listTags( Config const& config );
11168 
11169     std::size_t listReporters();
11170 
11171     Option<std::size_t> list( std::shared_ptr<Config> const& config );
11172 
11173 } // end namespace Catch
11174 
11175 // end catch_list.h
11176 // start catch_text.h
11177 
11178 namespace Catch {
11179     using namespace clara::TextFlow;
11180 }
11181 
11182 // end catch_text.h
11183 #include <limits>
11184 #include <algorithm>
11185 #include <iomanip>
11186 
11187 namespace Catch {
11188 
listTests(Config const & config)11189     std::size_t listTests( Config const& config ) {
11190         TestSpec const& testSpec = config.testSpec();
11191         if( config.hasTestFilters() )
11192             Catch::cout() << "Matching test cases:\n";
11193         else {
11194             Catch::cout() << "All available test cases:\n";
11195         }
11196 
11197         auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11198         for( auto const& testCaseInfo : matchedTestCases ) {
11199             Colour::Code colour = testCaseInfo.isHidden()
11200                 ? Colour::SecondaryText
11201                 : Colour::None;
11202             Colour colourGuard( colour );
11203 
11204             Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
11205             if( config.verbosity() >= Verbosity::High ) {
11206                 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11207                 std::string description = testCaseInfo.description;
11208                 if( description.empty() )
11209                     description = "(NO DESCRIPTION)";
11210                 Catch::cout() << Column( description ).indent(4) << std::endl;
11211             }
11212             if( !testCaseInfo.tags.empty() )
11213                 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
11214         }
11215 
11216         if( !config.hasTestFilters() )
11217             Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
11218         else
11219             Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
11220         return matchedTestCases.size();
11221     }
11222 
listTestsNamesOnly(Config const & config)11223     std::size_t listTestsNamesOnly( Config const& config ) {
11224         TestSpec const& testSpec = config.testSpec();
11225         std::size_t matchedTests = 0;
11226         std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11227         for( auto const& testCaseInfo : matchedTestCases ) {
11228             matchedTests++;
11229             if( startsWith( testCaseInfo.name, '#' ) )
11230                Catch::cout() << '"' << testCaseInfo.name << '"';
11231             else
11232                Catch::cout() << testCaseInfo.name;
11233             if ( config.verbosity() >= Verbosity::High )
11234                 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11235             Catch::cout() << std::endl;
11236         }
11237         return matchedTests;
11238     }
11239 
add(std::string const & spelling)11240     void TagInfo::add( std::string const& spelling ) {
11241         ++count;
11242         spellings.insert( spelling );
11243     }
11244 
all() const11245     std::string TagInfo::all() const {
11246         size_t size = 0;
11247         for (auto const& spelling : spellings) {
11248             // Add 2 for the brackes
11249             size += spelling.size() + 2;
11250         }
11251 
11252         std::string out; out.reserve(size);
11253         for (auto const& spelling : spellings) {
11254             out += '[';
11255             out += spelling;
11256             out += ']';
11257         }
11258         return out;
11259     }
11260 
listTags(Config const & config)11261     std::size_t listTags( Config const& config ) {
11262         TestSpec const& testSpec = config.testSpec();
11263         if( config.hasTestFilters() )
11264             Catch::cout() << "Tags for matching test cases:\n";
11265         else {
11266             Catch::cout() << "All available tags:\n";
11267         }
11268 
11269         std::map<std::string, TagInfo> tagCounts;
11270 
11271         std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11272         for( auto const& testCase : matchedTestCases ) {
11273             for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
11274                 std::string lcaseTagName = toLower( tagName );
11275                 auto countIt = tagCounts.find( lcaseTagName );
11276                 if( countIt == tagCounts.end() )
11277                     countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11278                 countIt->second.add( tagName );
11279             }
11280         }
11281 
11282         for( auto const& tagCount : tagCounts ) {
11283             ReusableStringStream rss;
11284             rss << "  " << std::setw(2) << tagCount.second.count << "  ";
11285             auto str = rss.str();
11286             auto wrapper = Column( tagCount.second.all() )
11287                                                     .initialIndent( 0 )
11288                                                     .indent( str.size() )
11289                                                     .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11290             Catch::cout() << str << wrapper << '\n';
11291         }
11292         Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
11293         return tagCounts.size();
11294     }
11295 
listReporters()11296     std::size_t listReporters() {
11297         Catch::cout() << "Available reporters:\n";
11298         IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
11299         std::size_t maxNameLen = 0;
11300         for( auto const& factoryKvp : factories )
11301             maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11302 
11303         for( auto const& factoryKvp : factories ) {
11304             Catch::cout()
11305                     << Column( factoryKvp.first + ":" )
11306                             .indent(2)
11307                             .width( 5+maxNameLen )
11308                     +  Column( factoryKvp.second->getDescription() )
11309                             .initialIndent(0)
11310                             .indent(2)
11311                             .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11312                     << "\n";
11313         }
11314         Catch::cout() << std::endl;
11315         return factories.size();
11316     }
11317 
list(std::shared_ptr<Config> const & config)11318     Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
11319         Option<std::size_t> listedCount;
11320         getCurrentMutableContext().setConfig( config );
11321         if( config->listTests() )
11322             listedCount = listedCount.valueOr(0) + listTests( *config );
11323         if( config->listTestNamesOnly() )
11324             listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11325         if( config->listTags() )
11326             listedCount = listedCount.valueOr(0) + listTags( *config );
11327         if( config->listReporters() )
11328             listedCount = listedCount.valueOr(0) + listReporters();
11329         return listedCount;
11330     }
11331 
11332 } // end namespace Catch
11333 // end catch_list.cpp
11334 // start catch_matchers.cpp
11335 
11336 namespace Catch {
11337 namespace Matchers {
11338     namespace Impl {
11339 
toString() const11340         std::string MatcherUntypedBase::toString() const {
11341             if( m_cachedToString.empty() )
11342                 m_cachedToString = describe();
11343             return m_cachedToString;
11344         }
11345 
11346         MatcherUntypedBase::~MatcherUntypedBase() = default;
11347 
11348     } // namespace Impl
11349 } // namespace Matchers
11350 
11351 using namespace Matchers;
11352 using Matchers::Impl::MatcherBase;
11353 
11354 } // namespace Catch
11355 // end catch_matchers.cpp
11356 // start catch_matchers_exception.cpp
11357 
11358 namespace Catch {
11359 namespace Matchers {
11360 namespace Exception {
11361 
match(std::exception const & ex) const11362 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11363     return ex.what() == m_message;
11364 }
11365 
describe() const11366 std::string ExceptionMessageMatcher::describe() const {
11367     return "exception message matches \"" + m_message + "\"";
11368 }
11369 
11370 }
Message(std::string const & message)11371 Exception::ExceptionMessageMatcher Message(std::string const& message) {
11372     return Exception::ExceptionMessageMatcher(message);
11373 }
11374 
11375 // namespace Exception
11376 } // namespace Matchers
11377 } // namespace Catch
11378 // end catch_matchers_exception.cpp
11379 // start catch_matchers_floating.cpp
11380 
11381 // start catch_polyfills.hpp
11382 
11383 namespace Catch {
11384     bool isnan(float f);
11385     bool isnan(double d);
11386 }
11387 
11388 // end catch_polyfills.hpp
11389 // start catch_to_string.hpp
11390 
11391 #include <string>
11392 
11393 namespace Catch {
11394     template <typename T>
to_string(T const & t)11395     std::string to_string(T const& t) {
11396 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11397         return std::to_string(t);
11398 #else
11399         ReusableStringStream rss;
11400         rss << t;
11401         return rss.str();
11402 #endif
11403     }
11404 } // end namespace Catch
11405 
11406 // end catch_to_string.hpp
11407 #include <algorithm>
11408 #include <cmath>
11409 #include <cstdlib>
11410 #include <cstdint>
11411 #include <cstring>
11412 #include <sstream>
11413 #include <type_traits>
11414 #include <iomanip>
11415 #include <limits>
11416 
11417 namespace Catch {
11418 namespace {
11419 
convert(float f)11420     int32_t convert(float f) {
11421         static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11422         int32_t i;
11423         std::memcpy(&i, &f, sizeof(f));
11424         return i;
11425     }
11426 
convert(double d)11427     int64_t convert(double d) {
11428         static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11429         int64_t i;
11430         std::memcpy(&i, &d, sizeof(d));
11431         return i;
11432     }
11433 
11434     template <typename FP>
almostEqualUlps(FP lhs,FP rhs,uint64_t maxUlpDiff)11435     bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11436         // Comparison with NaN should always be false.
11437         // This way we can rule it out before getting into the ugly details
11438         if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11439             return false;
11440         }
11441 
11442         auto lc = convert(lhs);
11443         auto rc = convert(rhs);
11444 
11445         if ((lc < 0) != (rc < 0)) {
11446             // Potentially we can have +0 and -0
11447             return lhs == rhs;
11448         }
11449 
11450         auto ulpDiff = std::abs(lc - rc);
11451         return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11452     }
11453 
11454 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11455 
nextafter(float x,float y)11456     float nextafter(float x, float y) {
11457         return ::nextafterf(x, y);
11458     }
11459 
nextafter(double x,double y)11460     double nextafter(double x, double y) {
11461         return ::nextafter(x, y);
11462     }
11463 
11464 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11465 
11466 template <typename FP>
step(FP start,FP direction,uint64_t steps)11467 FP step(FP start, FP direction, uint64_t steps) {
11468     for (uint64_t i = 0; i < steps; ++i) {
11469 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11470         start = Catch::nextafter(start, direction);
11471 #else
11472         start = std::nextafter(start, direction);
11473 #endif
11474     }
11475     return start;
11476 }
11477 
11478 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11479 // But without the subtraction to allow for INFINITY in comparison
marginComparison(double lhs,double rhs,double margin)11480 bool marginComparison(double lhs, double rhs, double margin) {
11481     return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11482 }
11483 
11484 template <typename FloatingPoint>
write(std::ostream & out,FloatingPoint num)11485 void write(std::ostream& out, FloatingPoint num) {
11486     out << std::scientific
11487         << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11488         << num;
11489 }
11490 
11491 } // end anonymous namespace
11492 
11493 namespace Matchers {
11494 namespace Floating {
11495 
11496     enum class FloatingPointKind : uint8_t {
11497         Float,
11498         Double
11499     };
11500 
WithinAbsMatcher(double target,double margin)11501     WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11502         :m_target{ target }, m_margin{ margin } {
11503         CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11504             << " Margin has to be non-negative.");
11505     }
11506 
11507     // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11508     // But without the subtraction to allow for INFINITY in comparison
match(double const & matchee) const11509     bool WithinAbsMatcher::match(double const& matchee) const {
11510         return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11511     }
11512 
describe() const11513     std::string WithinAbsMatcher::describe() const {
11514         return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11515     }
11516 
WithinUlpsMatcher(double target,uint64_t ulps,FloatingPointKind baseType)11517     WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11518         :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11519         CATCH_ENFORCE(m_type == FloatingPointKind::Double
11520                    || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11521             "Provided ULP is impossibly large for a float comparison.");
11522     }
11523 
11524 #if defined(__clang__)
11525 #pragma clang diagnostic push
11526 // Clang <3.5 reports on the default branch in the switch below
11527 #pragma clang diagnostic ignored "-Wunreachable-code"
11528 #endif
11529 
match(double const & matchee) const11530     bool WithinUlpsMatcher::match(double const& matchee) const {
11531         switch (m_type) {
11532         case FloatingPointKind::Float:
11533             return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11534         case FloatingPointKind::Double:
11535             return almostEqualUlps<double>(matchee, m_target, m_ulps);
11536         default:
11537             CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11538         }
11539     }
11540 
11541 #if defined(__clang__)
11542 #pragma clang diagnostic pop
11543 #endif
11544 
describe() const11545     std::string WithinUlpsMatcher::describe() const {
11546         std::stringstream ret;
11547 
11548         ret << "is within " << m_ulps << " ULPs of ";
11549 
11550         if (m_type == FloatingPointKind::Float) {
11551             write(ret, static_cast<float>(m_target));
11552             ret << 'f';
11553         } else {
11554             write(ret, m_target);
11555         }
11556 
11557         ret << " ([";
11558         if (m_type == FloatingPointKind::Double) {
11559             write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11560             ret << ", ";
11561             write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11562         } else {
11563             // We have to cast INFINITY to float because of MinGW, see #1782
11564             write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11565             ret << ", ";
11566             write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11567         }
11568         ret << "])";
11569 
11570         return ret.str();
11571     }
11572 
WithinRelMatcher(double target,double epsilon)11573     WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
11574         m_target(target),
11575         m_epsilon(epsilon){
11576         CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon <  0 does not make sense.");
11577         CATCH_ENFORCE(m_epsilon  < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11578     }
11579 
match(double const & matchee) const11580     bool WithinRelMatcher::match(double const& matchee) const {
11581         const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11582         return marginComparison(matchee, m_target,
11583                                 std::isinf(relMargin)? 0 : relMargin);
11584     }
11585 
describe() const11586     std::string WithinRelMatcher::describe() const {
11587         Catch::ReusableStringStream sstr;
11588         sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11589         return sstr.str();
11590     }
11591 
11592 }// namespace Floating
11593 
WithinULP(double target,uint64_t maxUlpDiff)11594 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11595     return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11596 }
11597 
WithinULP(float target,uint64_t maxUlpDiff)11598 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11599     return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11600 }
11601 
WithinAbs(double target,double margin)11602 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11603     return Floating::WithinAbsMatcher(target, margin);
11604 }
11605 
WithinRel(double target,double eps)11606 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11607     return Floating::WithinRelMatcher(target, eps);
11608 }
11609 
WithinRel(double target)11610 Floating::WithinRelMatcher WithinRel(double target) {
11611     return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11612 }
11613 
WithinRel(float target,float eps)11614 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11615     return Floating::WithinRelMatcher(target, eps);
11616 }
11617 
WithinRel(float target)11618 Floating::WithinRelMatcher WithinRel(float target) {
11619     return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11620 }
11621 
11622 } // namespace Matchers
11623 } // namespace Catch
11624 
11625 // end catch_matchers_floating.cpp
11626 // start catch_matchers_generic.cpp
11627 
finalizeDescription(const std::string & desc)11628 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11629     if (desc.empty()) {
11630         return "matches undescribed predicate";
11631     } else {
11632         return "matches predicate: \"" + desc + '"';
11633     }
11634 }
11635 // end catch_matchers_generic.cpp
11636 // start catch_matchers_string.cpp
11637 
11638 #include <regex>
11639 
11640 namespace Catch {
11641 namespace Matchers {
11642 
11643     namespace StdString {
11644 
CasedString(std::string const & str,CaseSensitive::Choice caseSensitivity)11645         CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11646         :   m_caseSensitivity( caseSensitivity ),
11647             m_str( adjustString( str ) )
11648         {}
adjustString(std::string const & str) const11649         std::string CasedString::adjustString( std::string const& str ) const {
11650             return m_caseSensitivity == CaseSensitive::No
11651                    ? toLower( str )
11652                    : str;
11653         }
caseSensitivitySuffix() const11654         std::string CasedString::caseSensitivitySuffix() const {
11655             return m_caseSensitivity == CaseSensitive::No
11656                    ? " (case insensitive)"
11657                    : std::string();
11658         }
11659 
StringMatcherBase(std::string const & operation,CasedString const & comparator)11660         StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11661         : m_comparator( comparator ),
11662           m_operation( operation ) {
11663         }
11664 
describe() const11665         std::string StringMatcherBase::describe() const {
11666             std::string description;
11667             description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11668                                         m_comparator.caseSensitivitySuffix().size());
11669             description += m_operation;
11670             description += ": \"";
11671             description += m_comparator.m_str;
11672             description += "\"";
11673             description += m_comparator.caseSensitivitySuffix();
11674             return description;
11675         }
11676 
EqualsMatcher(CasedString const & comparator)11677         EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11678 
match(std::string const & source) const11679         bool EqualsMatcher::match( std::string const& source ) const {
11680             return m_comparator.adjustString( source ) == m_comparator.m_str;
11681         }
11682 
ContainsMatcher(CasedString const & comparator)11683         ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11684 
match(std::string const & source) const11685         bool ContainsMatcher::match( std::string const& source ) const {
11686             return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11687         }
11688 
StartsWithMatcher(CasedString const & comparator)11689         StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11690 
match(std::string const & source) const11691         bool StartsWithMatcher::match( std::string const& source ) const {
11692             return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11693         }
11694 
EndsWithMatcher(CasedString const & comparator)11695         EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11696 
match(std::string const & source) const11697         bool EndsWithMatcher::match( std::string const& source ) const {
11698             return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11699         }
11700 
RegexMatcher(std::string regex,CaseSensitive::Choice caseSensitivity)11701         RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11702 
match(std::string const & matchee) const11703         bool RegexMatcher::match(std::string const& matchee) const {
11704             auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11705             if (m_caseSensitivity == CaseSensitive::Choice::No) {
11706                 flags |= std::regex::icase;
11707             }
11708             auto reg = std::regex(m_regex, flags);
11709             return std::regex_match(matchee, reg);
11710         }
11711 
describe() const11712         std::string RegexMatcher::describe() const {
11713             return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11714         }
11715 
11716     } // namespace StdString
11717 
Equals(std::string const & str,CaseSensitive::Choice caseSensitivity)11718     StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11719         return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11720     }
Contains(std::string const & str,CaseSensitive::Choice caseSensitivity)11721     StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11722         return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11723     }
EndsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11724     StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11725         return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11726     }
StartsWith(std::string const & str,CaseSensitive::Choice caseSensitivity)11727     StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11728         return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11729     }
11730 
Matches(std::string const & regex,CaseSensitive::Choice caseSensitivity)11731     StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11732         return StdString::RegexMatcher(regex, caseSensitivity);
11733     }
11734 
11735 } // namespace Matchers
11736 } // namespace Catch
11737 // end catch_matchers_string.cpp
11738 // start catch_message.cpp
11739 
11740 // start catch_uncaught_exceptions.h
11741 
11742 namespace Catch {
11743     bool uncaught_exceptions();
11744 } // end namespace Catch
11745 
11746 // end catch_uncaught_exceptions.h
11747 #include <cassert>
11748 #include <stack>
11749 
11750 namespace Catch {
11751 
MessageInfo(StringRef const & _macroName,SourceLineInfo const & _lineInfo,ResultWas::OfType _type)11752     MessageInfo::MessageInfo(   StringRef const& _macroName,
11753                                 SourceLineInfo const& _lineInfo,
11754                                 ResultWas::OfType _type )
11755     :   macroName( _macroName ),
11756         lineInfo( _lineInfo ),
11757         type( _type ),
11758         sequence( ++globalCount )
11759     {}
11760 
operator ==(MessageInfo const & other) const11761     bool MessageInfo::operator==( MessageInfo const& other ) const {
11762         return sequence == other.sequence;
11763     }
11764 
operator <(MessageInfo const & other) const11765     bool MessageInfo::operator<( MessageInfo const& other ) const {
11766         return sequence < other.sequence;
11767     }
11768 
11769     // This may need protecting if threading support is added
11770     unsigned int MessageInfo::globalCount = 0;
11771 
11772     ////////////////////////////////////////////////////////////////////////////
11773 
MessageBuilder(StringRef const & macroName,SourceLineInfo const & lineInfo,ResultWas::OfType type)11774     Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11775                                            SourceLineInfo const& lineInfo,
11776                                            ResultWas::OfType type )
11777         :m_info(macroName, lineInfo, type) {}
11778 
11779     ////////////////////////////////////////////////////////////////////////////
11780 
ScopedMessage(MessageBuilder const & builder)11781     ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11782     : m_info( builder.m_info ), m_moved()
11783     {
11784         m_info.message = builder.m_stream.str();
11785         getResultCapture().pushScopedMessage( m_info );
11786     }
11787 
ScopedMessage(ScopedMessage && old)11788     ScopedMessage::ScopedMessage( ScopedMessage&& old )
11789     : m_info( old.m_info ), m_moved()
11790     {
11791         old.m_moved = true;
11792     }
11793 
~ScopedMessage()11794     ScopedMessage::~ScopedMessage() {
11795         if ( !uncaught_exceptions() && !m_moved ){
11796             getResultCapture().popScopedMessage(m_info);
11797         }
11798     }
11799 
Capturer(StringRef macroName,SourceLineInfo const & lineInfo,ResultWas::OfType resultType,StringRef names)11800     Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11801         auto trimmed = [&] (size_t start, size_t end) {
11802             while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11803                 ++start;
11804             }
11805             while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11806                 --end;
11807             }
11808             return names.substr(start, end - start + 1);
11809         };
11810         auto skipq = [&] (size_t start, char quote) {
11811             for (auto i = start + 1; i < names.size() ; ++i) {
11812                 if (names[i] == quote)
11813                     return i;
11814                 if (names[i] == '\\')
11815                     ++i;
11816             }
11817             CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11818         };
11819 
11820         size_t start = 0;
11821         std::stack<char> openings;
11822         for (size_t pos = 0; pos < names.size(); ++pos) {
11823             char c = names[pos];
11824             switch (c) {
11825             case '[':
11826             case '{':
11827             case '(':
11828             // It is basically impossible to disambiguate between
11829             // comparison and start of template args in this context
11830 //            case '<':
11831                 openings.push(c);
11832                 break;
11833             case ']':
11834             case '}':
11835             case ')':
11836 //           case '>':
11837                 openings.pop();
11838                 break;
11839             case '"':
11840             case '\'':
11841                 pos = skipq(pos, c);
11842                 break;
11843             case ',':
11844                 if (start != pos && openings.empty()) {
11845                     m_messages.emplace_back(macroName, lineInfo, resultType);
11846                     m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11847                     m_messages.back().message += " := ";
11848                     start = pos;
11849                 }
11850             }
11851         }
11852         assert(openings.empty() && "Mismatched openings");
11853         m_messages.emplace_back(macroName, lineInfo, resultType);
11854         m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11855         m_messages.back().message += " := ";
11856     }
~Capturer()11857     Capturer::~Capturer() {
11858         if ( !uncaught_exceptions() ){
11859             assert( m_captured == m_messages.size() );
11860             for( size_t i = 0; i < m_captured; ++i  )
11861                 m_resultCapture.popScopedMessage( m_messages[i] );
11862         }
11863     }
11864 
captureValue(size_t index,std::string const & value)11865     void Capturer::captureValue( size_t index, std::string const& value ) {
11866         assert( index < m_messages.size() );
11867         m_messages[index].message += value;
11868         m_resultCapture.pushScopedMessage( m_messages[index] );
11869         m_captured++;
11870     }
11871 
11872 } // end namespace Catch
11873 // end catch_message.cpp
11874 // start catch_output_redirect.cpp
11875 
11876 // start catch_output_redirect.h
11877 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11878 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11879 
11880 #include <cstdio>
11881 #include <iosfwd>
11882 #include <string>
11883 
11884 namespace Catch {
11885 
11886     class RedirectedStream {
11887         std::ostream& m_originalStream;
11888         std::ostream& m_redirectionStream;
11889         std::streambuf* m_prevBuf;
11890 
11891     public:
11892         RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11893         ~RedirectedStream();
11894     };
11895 
11896     class RedirectedStdOut {
11897         ReusableStringStream m_rss;
11898         RedirectedStream m_cout;
11899     public:
11900         RedirectedStdOut();
11901         auto str() const -> std::string;
11902     };
11903 
11904     // StdErr has two constituent streams in C++, std::cerr and std::clog
11905     // This means that we need to redirect 2 streams into 1 to keep proper
11906     // order of writes
11907     class RedirectedStdErr {
11908         ReusableStringStream m_rss;
11909         RedirectedStream m_cerr;
11910         RedirectedStream m_clog;
11911     public:
11912         RedirectedStdErr();
11913         auto str() const -> std::string;
11914     };
11915 
11916     class RedirectedStreams {
11917     public:
11918         RedirectedStreams(RedirectedStreams const&) = delete;
11919         RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11920         RedirectedStreams(RedirectedStreams&&) = delete;
11921         RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11922 
11923         RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11924         ~RedirectedStreams();
11925     private:
11926         std::string& m_redirectedCout;
11927         std::string& m_redirectedCerr;
11928         RedirectedStdOut m_redirectedStdOut;
11929         RedirectedStdErr m_redirectedStdErr;
11930     };
11931 
11932 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11933 
11934     // Windows's implementation of std::tmpfile is terrible (it tries
11935     // to create a file inside system folder, thus requiring elevated
11936     // privileges for the binary), so we have to use tmpnam(_s) and
11937     // create the file ourselves there.
11938     class TempFile {
11939     public:
11940         TempFile(TempFile const&) = delete;
11941         TempFile& operator=(TempFile const&) = delete;
11942         TempFile(TempFile&&) = delete;
11943         TempFile& operator=(TempFile&&) = delete;
11944 
11945         TempFile();
11946         ~TempFile();
11947 
11948         std::FILE* getFile();
11949         std::string getContents();
11950 
11951     private:
11952         std::FILE* m_file = nullptr;
11953     #if defined(_MSC_VER)
11954         char m_buffer[L_tmpnam] = { 0 };
11955     #endif
11956     };
11957 
11958     class OutputRedirect {
11959     public:
11960         OutputRedirect(OutputRedirect const&) = delete;
11961         OutputRedirect& operator=(OutputRedirect const&) = delete;
11962         OutputRedirect(OutputRedirect&&) = delete;
11963         OutputRedirect& operator=(OutputRedirect&&) = delete;
11964 
11965         OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
11966         ~OutputRedirect();
11967 
11968     private:
11969         int m_originalStdout = -1;
11970         int m_originalStderr = -1;
11971         TempFile m_stdoutFile;
11972         TempFile m_stderrFile;
11973         std::string& m_stdoutDest;
11974         std::string& m_stderrDest;
11975     };
11976 
11977 #endif
11978 
11979 } // end namespace Catch
11980 
11981 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11982 // end catch_output_redirect.h
11983 #include <cstdio>
11984 #include <cstring>
11985 #include <fstream>
11986 #include <sstream>
11987 #include <stdexcept>
11988 
11989 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11990     #if defined(_MSC_VER)
11991     #include <io.h>      //_dup and _dup2
11992     #define dup _dup
11993     #define dup2 _dup2
11994     #define fileno _fileno
11995     #else
11996     #include <unistd.h>  // dup and dup2
11997     #endif
11998 #endif
11999 
12000 namespace Catch {
12001 
RedirectedStream(std::ostream & originalStream,std::ostream & redirectionStream)12002     RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12003     :   m_originalStream( originalStream ),
12004         m_redirectionStream( redirectionStream ),
12005         m_prevBuf( m_originalStream.rdbuf() )
12006     {
12007         m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12008     }
12009 
~RedirectedStream()12010     RedirectedStream::~RedirectedStream() {
12011         m_originalStream.rdbuf( m_prevBuf );
12012     }
12013 
RedirectedStdOut()12014     RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
str() const12015     auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12016 
RedirectedStdErr()12017     RedirectedStdErr::RedirectedStdErr()
12018     :   m_cerr( Catch::cerr(), m_rss.get() ),
12019         m_clog( Catch::clog(), m_rss.get() )
12020     {}
str() const12021     auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12022 
RedirectedStreams(std::string & redirectedCout,std::string & redirectedCerr)12023     RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12024     :   m_redirectedCout(redirectedCout),
12025         m_redirectedCerr(redirectedCerr)
12026     {}
12027 
~RedirectedStreams()12028     RedirectedStreams::~RedirectedStreams() {
12029         m_redirectedCout += m_redirectedStdOut.str();
12030         m_redirectedCerr += m_redirectedStdErr.str();
12031     }
12032 
12033 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12034 
12035 #if defined(_MSC_VER)
TempFile()12036     TempFile::TempFile() {
12037         if (tmpnam_s(m_buffer)) {
12038             CATCH_RUNTIME_ERROR("Could not get a temp filename");
12039         }
12040         if (fopen_s(&m_file, m_buffer, "w+")) {
12041             char buffer[100];
12042             if (strerror_s(buffer, errno)) {
12043                 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12044             }
12045             CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12046         }
12047     }
12048 #else
TempFile()12049     TempFile::TempFile() {
12050         m_file = std::tmpfile();
12051         if (!m_file) {
12052             CATCH_RUNTIME_ERROR("Could not create a temp file.");
12053         }
12054     }
12055 
12056 #endif
12057 
~TempFile()12058     TempFile::~TempFile() {
12059          // TBD: What to do about errors here?
12060          std::fclose(m_file);
12061          // We manually create the file on Windows only, on Linux
12062          // it will be autodeleted
12063 #if defined(_MSC_VER)
12064          std::remove(m_buffer);
12065 #endif
12066     }
12067 
getFile()12068     FILE* TempFile::getFile() {
12069         return m_file;
12070     }
12071 
getContents()12072     std::string TempFile::getContents() {
12073         std::stringstream sstr;
12074         char buffer[100] = {};
12075         std::rewind(m_file);
12076         while (std::fgets(buffer, sizeof(buffer), m_file)) {
12077             sstr << buffer;
12078         }
12079         return sstr.str();
12080     }
12081 
OutputRedirect(std::string & stdout_dest,std::string & stderr_dest)12082     OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12083         m_originalStdout(dup(1)),
12084         m_originalStderr(dup(2)),
12085         m_stdoutDest(stdout_dest),
12086         m_stderrDest(stderr_dest) {
12087         dup2(fileno(m_stdoutFile.getFile()), 1);
12088         dup2(fileno(m_stderrFile.getFile()), 2);
12089     }
12090 
~OutputRedirect()12091     OutputRedirect::~OutputRedirect() {
12092         Catch::cout() << std::flush;
12093         fflush(stdout);
12094         // Since we support overriding these streams, we flush cerr
12095         // even though std::cerr is unbuffered
12096         Catch::cerr() << std::flush;
12097         Catch::clog() << std::flush;
12098         fflush(stderr);
12099 
12100         dup2(m_originalStdout, 1);
12101         dup2(m_originalStderr, 2);
12102 
12103         m_stdoutDest += m_stdoutFile.getContents();
12104         m_stderrDest += m_stderrFile.getContents();
12105     }
12106 
12107 #endif // CATCH_CONFIG_NEW_CAPTURE
12108 
12109 } // namespace Catch
12110 
12111 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12112     #if defined(_MSC_VER)
12113     #undef dup
12114     #undef dup2
12115     #undef fileno
12116     #endif
12117 #endif
12118 // end catch_output_redirect.cpp
12119 // start catch_polyfills.cpp
12120 
12121 #include <cmath>
12122 
12123 namespace Catch {
12124 
12125 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
isnan(float f)12126     bool isnan(float f) {
12127         return std::isnan(f);
12128     }
isnan(double d)12129     bool isnan(double d) {
12130         return std::isnan(d);
12131     }
12132 #else
12133     // For now we only use this for embarcadero
12134     bool isnan(float f) {
12135         return std::_isnan(f);
12136     }
12137     bool isnan(double d) {
12138         return std::_isnan(d);
12139     }
12140 #endif
12141 
12142 } // end namespace Catch
12143 // end catch_polyfills.cpp
12144 // start catch_random_number_generator.cpp
12145 
12146 namespace Catch {
12147 
12148 namespace {
12149 
12150 #if defined(_MSC_VER)
12151 #pragma warning(push)
12152 #pragma warning(disable:4146) // we negate uint32 during the rotate
12153 #endif
12154         // Safe rotr implementation thanks to John Regehr
rotate_right(uint32_t val,uint32_t count)12155         uint32_t rotate_right(uint32_t val, uint32_t count) {
12156             const uint32_t mask = 31;
12157             count &= mask;
12158             return (val >> count) | (val << (-count & mask));
12159         }
12160 
12161 #if defined(_MSC_VER)
12162 #pragma warning(pop)
12163 #endif
12164 
12165 }
12166 
SimplePcg32(result_type seed_)12167     SimplePcg32::SimplePcg32(result_type seed_) {
12168         seed(seed_);
12169     }
12170 
seed(result_type seed_)12171     void SimplePcg32::seed(result_type seed_) {
12172         m_state = 0;
12173         (*this)();
12174         m_state += seed_;
12175         (*this)();
12176     }
12177 
discard(uint64_t skip)12178     void SimplePcg32::discard(uint64_t skip) {
12179         // We could implement this to run in O(log n) steps, but this
12180         // should suffice for our use case.
12181         for (uint64_t s = 0; s < skip; ++s) {
12182             static_cast<void>((*this)());
12183         }
12184     }
12185 
operator ()()12186     SimplePcg32::result_type SimplePcg32::operator()() {
12187         // prepare the output value
12188         const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12189         const auto output = rotate_right(xorshifted, m_state >> 59u);
12190 
12191         // advance state
12192         m_state = m_state * 6364136223846793005ULL + s_inc;
12193 
12194         return output;
12195     }
12196 
operator ==(SimplePcg32 const & lhs,SimplePcg32 const & rhs)12197     bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12198         return lhs.m_state == rhs.m_state;
12199     }
12200 
operator !=(SimplePcg32 const & lhs,SimplePcg32 const & rhs)12201     bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12202         return lhs.m_state != rhs.m_state;
12203     }
12204 }
12205 // end catch_random_number_generator.cpp
12206 // start catch_registry_hub.cpp
12207 
12208 // start catch_test_case_registry_impl.h
12209 
12210 #include <vector>
12211 #include <set>
12212 #include <algorithm>
12213 #include <ios>
12214 
12215 namespace Catch {
12216 
12217     class TestCase;
12218     struct IConfig;
12219 
12220     std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
12221 
12222     bool isThrowSafe( TestCase const& testCase, IConfig const& config );
12223     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
12224 
12225     void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
12226 
12227     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
12228     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
12229 
12230     class TestRegistry : public ITestCaseRegistry {
12231     public:
12232         virtual ~TestRegistry() = default;
12233 
12234         virtual void registerTest( TestCase const& testCase );
12235 
12236         std::vector<TestCase> const& getAllTests() const override;
12237         std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
12238 
12239     private:
12240         std::vector<TestCase> m_functions;
12241         mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12242         mutable std::vector<TestCase> m_sortedFunctions;
12243         std::size_t m_unnamedCount = 0;
12244         std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12245     };
12246 
12247     ///////////////////////////////////////////////////////////////////////////
12248 
12249     class TestInvokerAsFunction : public ITestInvoker {
12250         void(*m_testAsFunction)();
12251     public:
12252         TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
12253 
12254         void invoke() const override;
12255     };
12256 
12257     std::string extractClassName( StringRef const& classOrQualifiedMethodName );
12258 
12259     ///////////////////////////////////////////////////////////////////////////
12260 
12261 } // end namespace Catch
12262 
12263 // end catch_test_case_registry_impl.h
12264 // start catch_reporter_registry.h
12265 
12266 #include <map>
12267 
12268 namespace Catch {
12269 
12270     class ReporterRegistry : public IReporterRegistry {
12271 
12272     public:
12273 
12274         ~ReporterRegistry() override;
12275 
12276         IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
12277 
12278         void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
12279         void registerListener( IReporterFactoryPtr const& factory );
12280 
12281         FactoryMap const& getFactories() const override;
12282         Listeners const& getListeners() const override;
12283 
12284     private:
12285         FactoryMap m_factories;
12286         Listeners m_listeners;
12287     };
12288 }
12289 
12290 // end catch_reporter_registry.h
12291 // start catch_tag_alias_registry.h
12292 
12293 // start catch_tag_alias.h
12294 
12295 #include <string>
12296 
12297 namespace Catch {
12298 
12299     struct TagAlias {
12300         TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12301 
12302         std::string tag;
12303         SourceLineInfo lineInfo;
12304     };
12305 
12306 } // end namespace Catch
12307 
12308 // end catch_tag_alias.h
12309 #include <map>
12310 
12311 namespace Catch {
12312 
12313     class TagAliasRegistry : public ITagAliasRegistry {
12314     public:
12315         ~TagAliasRegistry() override;
12316         TagAlias const* find( std::string const& alias ) const override;
12317         std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
12318         void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
12319 
12320     private:
12321         std::map<std::string, TagAlias> m_registry;
12322     };
12323 
12324 } // end namespace Catch
12325 
12326 // end catch_tag_alias_registry.h
12327 // start catch_startup_exception_registry.h
12328 
12329 #include <vector>
12330 #include <exception>
12331 
12332 namespace Catch {
12333 
12334     class StartupExceptionRegistry {
12335 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12336     public:
12337         void add(std::exception_ptr const& exception) noexcept;
12338         std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12339     private:
12340         std::vector<std::exception_ptr> m_exceptions;
12341 #endif
12342     };
12343 
12344 } // end namespace Catch
12345 
12346 // end catch_startup_exception_registry.h
12347 // start catch_singletons.hpp
12348 
12349 namespace Catch {
12350 
12351     struct ISingleton {
12352         virtual ~ISingleton();
12353     };
12354 
12355     void addSingleton( ISingleton* singleton );
12356     void cleanupSingletons();
12357 
12358     template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
12359     class Singleton : SingletonImplT, public ISingleton {
12360 
getInternal()12361         static auto getInternal() -> Singleton* {
12362             static Singleton* s_instance = nullptr;
12363             if( !s_instance ) {
12364                 s_instance = new Singleton;
12365                 addSingleton( s_instance );
12366             }
12367             return s_instance;
12368         }
12369 
12370     public:
get()12371         static auto get() -> InterfaceT const& {
12372             return *getInternal();
12373         }
getMutable()12374         static auto getMutable() -> MutableInterfaceT& {
12375             return *getInternal();
12376         }
12377     };
12378 
12379 } // namespace Catch
12380 
12381 // end catch_singletons.hpp
12382 namespace Catch {
12383 
12384     namespace {
12385 
12386         class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
12387                             private NonCopyable {
12388 
12389         public: // IRegistryHub
12390             RegistryHub() = default;
getReporterRegistry() const12391             IReporterRegistry const& getReporterRegistry() const override {
12392                 return m_reporterRegistry;
12393             }
getTestCaseRegistry() const12394             ITestCaseRegistry const& getTestCaseRegistry() const override {
12395                 return m_testCaseRegistry;
12396             }
getExceptionTranslatorRegistry() const12397             IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12398                 return m_exceptionTranslatorRegistry;
12399             }
getTagAliasRegistry() const12400             ITagAliasRegistry const& getTagAliasRegistry() const override {
12401                 return m_tagAliasRegistry;
12402             }
getStartupExceptionRegistry() const12403             StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12404                 return m_exceptionRegistry;
12405             }
12406 
12407         public: // IMutableRegistryHub
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)12408             void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
12409                 m_reporterRegistry.registerReporter( name, factory );
12410             }
registerListener(IReporterFactoryPtr const & factory)12411             void registerListener( IReporterFactoryPtr const& factory ) override {
12412                 m_reporterRegistry.registerListener( factory );
12413             }
registerTest(TestCase const & testInfo)12414             void registerTest( TestCase const& testInfo ) override {
12415                 m_testCaseRegistry.registerTest( testInfo );
12416             }
registerTranslator(const IExceptionTranslator * translator)12417             void registerTranslator( const IExceptionTranslator* translator ) override {
12418                 m_exceptionTranslatorRegistry.registerTranslator( translator );
12419             }
registerTagAlias(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)12420             void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
12421                 m_tagAliasRegistry.add( alias, tag, lineInfo );
12422             }
registerStartupException()12423             void registerStartupException() noexcept override {
12424 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12425                 m_exceptionRegistry.add(std::current_exception());
12426 #else
12427                 CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12428 #endif
12429             }
getMutableEnumValuesRegistry()12430             IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12431                 return m_enumValuesRegistry;
12432             }
12433 
12434         private:
12435             TestRegistry m_testCaseRegistry;
12436             ReporterRegistry m_reporterRegistry;
12437             ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12438             TagAliasRegistry m_tagAliasRegistry;
12439             StartupExceptionRegistry m_exceptionRegistry;
12440             Detail::EnumValuesRegistry m_enumValuesRegistry;
12441         };
12442     }
12443 
12444     using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12445 
getRegistryHub()12446     IRegistryHub const& getRegistryHub() {
12447         return RegistryHubSingleton::get();
12448     }
getMutableRegistryHub()12449     IMutableRegistryHub& getMutableRegistryHub() {
12450         return RegistryHubSingleton::getMutable();
12451     }
cleanUp()12452     void cleanUp() {
12453         cleanupSingletons();
12454         cleanUpContext();
12455     }
translateActiveException()12456     std::string translateActiveException() {
12457         return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12458     }
12459 
12460 } // end namespace Catch
12461 // end catch_registry_hub.cpp
12462 // start catch_reporter_registry.cpp
12463 
12464 namespace Catch {
12465 
12466     ReporterRegistry::~ReporterRegistry() = default;
12467 
create(std::string const & name,IConfigPtr const & config) const12468     IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
12469         auto it =  m_factories.find( name );
12470         if( it == m_factories.end() )
12471             return nullptr;
12472         return it->second->create( ReporterConfig( config ) );
12473     }
12474 
registerReporter(std::string const & name,IReporterFactoryPtr const & factory)12475     void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12476         m_factories.emplace(name, factory);
12477     }
registerListener(IReporterFactoryPtr const & factory)12478     void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12479         m_listeners.push_back( factory );
12480     }
12481 
getFactories() const12482     IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12483         return m_factories;
12484     }
getListeners() const12485     IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12486         return m_listeners;
12487     }
12488 
12489 }
12490 // end catch_reporter_registry.cpp
12491 // start catch_result_type.cpp
12492 
12493 namespace Catch {
12494 
isOk(ResultWas::OfType resultType)12495     bool isOk( ResultWas::OfType resultType ) {
12496         return ( resultType & ResultWas::FailureBit ) == 0;
12497     }
isJustInfo(int flags)12498     bool isJustInfo( int flags ) {
12499         return flags == ResultWas::Info;
12500     }
12501 
operator |(ResultDisposition::Flags lhs,ResultDisposition::Flags rhs)12502     ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12503         return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12504     }
12505 
shouldContinueOnFailure(int flags)12506     bool shouldContinueOnFailure( int flags )    { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
shouldSuppressFailure(int flags)12507     bool shouldSuppressFailure( int flags )      { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12508 
12509 } // end namespace Catch
12510 // end catch_result_type.cpp
12511 // start catch_run_context.cpp
12512 
12513 #include <cassert>
12514 #include <algorithm>
12515 #include <sstream>
12516 
12517 namespace Catch {
12518 
12519     namespace Generators {
12520         struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12521             GeneratorBasePtr m_generator;
12522 
GeneratorTrackerCatch::Generators::GeneratorTracker12523             GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12524             :   TrackerBase( nameAndLocation, ctx, parent )
12525             {}
12526             ~GeneratorTracker();
12527 
acquireCatch::Generators::GeneratorTracker12528             static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12529                 std::shared_ptr<GeneratorTracker> tracker;
12530 
12531                 ITracker& currentTracker = ctx.currentTracker();
12532                 // Under specific circumstances, the generator we want
12533                 // to acquire is also the current tracker. If this is
12534                 // the case, we have to avoid looking through current
12535                 // tracker's children, and instead return the current
12536                 // tracker.
12537                 // A case where this check is important is e.g.
12538                 //     for (int i = 0; i < 5; ++i) {
12539                 //         int n = GENERATE(1, 2);
12540                 //     }
12541                 //
12542                 // without it, the code above creates 5 nested generators.
12543                 if (currentTracker.nameAndLocation() == nameAndLocation) {
12544                     auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12545                     assert(thisTracker);
12546                     assert(thisTracker->isGeneratorTracker());
12547                     tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12548                 } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12549                     assert( childTracker );
12550                     assert( childTracker->isGeneratorTracker() );
12551                     tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12552                 } else {
12553                     tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
12554                     currentTracker.addChild( tracker );
12555                 }
12556 
12557                 if( !tracker->isComplete() ) {
12558                     tracker->open();
12559                 }
12560 
12561                 return *tracker;
12562             }
12563 
12564             // TrackerBase interface
isGeneratorTrackerCatch::Generators::GeneratorTracker12565             bool isGeneratorTracker() const override { return true; }
hasGeneratorCatch::Generators::GeneratorTracker12566             auto hasGenerator() const -> bool override {
12567                 return !!m_generator;
12568             }
closeCatch::Generators::GeneratorTracker12569             void close() override {
12570                 TrackerBase::close();
12571                 // If a generator has a child (it is followed by a section)
12572                 // and none of its children have started, then we must wait
12573                 // until later to start consuming its values.
12574                 // This catches cases where `GENERATE` is placed between two
12575                 // `SECTION`s.
12576                 // **The check for m_children.empty cannot be removed**.
12577                 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12578                 const bool should_wait_for_child = [&]() {
12579                     // No children -> nobody to wait for
12580                     if ( m_children.empty() ) {
12581                         return false;
12582                     }
12583                     // If at least one child started executing, don't wait
12584                     if ( std::find_if(
12585                              m_children.begin(),
12586                              m_children.end(),
12587                              []( TestCaseTracking::ITrackerPtr tracker ) {
12588                                  return tracker->hasStarted();
12589                              } ) != m_children.end() ) {
12590                         return false;
12591                     }
12592 
12593                     // No children have started. We need to check if they _can_
12594                     // start, and thus we should wait for them, or they cannot
12595                     // start (due to filters), and we shouldn't wait for them
12596                     auto* parent = m_parent;
12597                     // This is safe: there is always at least one section
12598                     // tracker in a test case tracking tree
12599                     while ( !parent->isSectionTracker() ) {
12600                         parent = &( parent->parent() );
12601                     }
12602                     assert( parent &&
12603                             "Missing root (test case) level section" );
12604 
12605                     auto const& parentSection =
12606                         static_cast<SectionTracker&>( *parent );
12607                     auto const& filters = parentSection.getFilters();
12608                     // No filters -> no restrictions on running sections
12609                     if ( filters.empty() ) {
12610                         return true;
12611                     }
12612 
12613                     for ( auto const& child : m_children ) {
12614                         if ( child->isSectionTracker() &&
12615                              std::find( filters.begin(),
12616                                         filters.end(),
12617                                         static_cast<SectionTracker&>( *child )
12618                                             .trimmedName() ) !=
12619                                  filters.end() ) {
12620                             return true;
12621                         }
12622                     }
12623                     return false;
12624                 }();
12625 
12626                 // This check is a bit tricky, because m_generator->next()
12627                 // has a side-effect, where it consumes generator's current
12628                 // value, but we do not want to invoke the side-effect if
12629                 // this generator is still waiting for any child to start.
12630                 if ( should_wait_for_child ||
12631                      ( m_runState == CompletedSuccessfully &&
12632                        m_generator->next() ) ) {
12633                     m_children.clear();
12634                     m_runState = Executing;
12635                 }
12636             }
12637 
12638             // IGeneratorTracker interface
getGeneratorCatch::Generators::GeneratorTracker12639             auto getGenerator() const -> GeneratorBasePtr const& override {
12640                 return m_generator;
12641             }
setGeneratorCatch::Generators::GeneratorTracker12642             void setGenerator( GeneratorBasePtr&& generator ) override {
12643                 m_generator = std::move( generator );
12644             }
12645         };
~GeneratorTracker()12646         GeneratorTracker::~GeneratorTracker() {}
12647     }
12648 
RunContext(IConfigPtr const & _config,IStreamingReporterPtr && reporter)12649     RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12650     :   m_runInfo(_config->name()),
12651         m_context(getCurrentMutableContext()),
12652         m_config(_config),
12653         m_reporter(std::move(reporter)),
12654         m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12655         m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12656     {
12657         m_context.setRunner(this);
12658         m_context.setConfig(m_config);
12659         m_context.setResultCapture(this);
12660         m_reporter->testRunStarting(m_runInfo);
12661     }
12662 
~RunContext()12663     RunContext::~RunContext() {
12664         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12665     }
12666 
testGroupStarting(std::string const & testSpec,std::size_t groupIndex,std::size_t groupsCount)12667     void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12668         m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12669     }
12670 
testGroupEnded(std::string const & testSpec,Totals const & totals,std::size_t groupIndex,std::size_t groupsCount)12671     void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12672         m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12673     }
12674 
runTest(TestCase const & testCase)12675     Totals RunContext::runTest(TestCase const& testCase) {
12676         Totals prevTotals = m_totals;
12677 
12678         std::string redirectedCout;
12679         std::string redirectedCerr;
12680 
12681         auto const& testInfo = testCase.getTestCaseInfo();
12682 
12683         m_reporter->testCaseStarting(testInfo);
12684 
12685         m_activeTestCase = &testCase;
12686 
12687         ITracker& rootTracker = m_trackerContext.startRun();
12688         assert(rootTracker.isSectionTracker());
12689         static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12690         do {
12691             m_trackerContext.startCycle();
12692             m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12693             runCurrentTest(redirectedCout, redirectedCerr);
12694         } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12695 
12696         Totals deltaTotals = m_totals.delta(prevTotals);
12697         if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12698             deltaTotals.assertions.failed++;
12699             deltaTotals.testCases.passed--;
12700             deltaTotals.testCases.failed++;
12701         }
12702         m_totals.testCases += deltaTotals.testCases;
12703         m_reporter->testCaseEnded(TestCaseStats(testInfo,
12704                                   deltaTotals,
12705                                   redirectedCout,
12706                                   redirectedCerr,
12707                                   aborting()));
12708 
12709         m_activeTestCase = nullptr;
12710         m_testCaseTracker = nullptr;
12711 
12712         return deltaTotals;
12713     }
12714 
config() const12715     IConfigPtr RunContext::config() const {
12716         return m_config;
12717     }
12718 
reporter() const12719     IStreamingReporter& RunContext::reporter() const {
12720         return *m_reporter;
12721     }
12722 
assertionEnded(AssertionResult const & result)12723     void RunContext::assertionEnded(AssertionResult const & result) {
12724         if (result.getResultType() == ResultWas::Ok) {
12725             m_totals.assertions.passed++;
12726             m_lastAssertionPassed = true;
12727         } else if (!result.isOk()) {
12728             m_lastAssertionPassed = false;
12729             if( m_activeTestCase->getTestCaseInfo().okToFail() )
12730                 m_totals.assertions.failedButOk++;
12731             else
12732                 m_totals.assertions.failed++;
12733         }
12734         else {
12735             m_lastAssertionPassed = true;
12736         }
12737 
12738         // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12739         // and should be let to clear themselves out.
12740         static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12741 
12742         if (result.getResultType() != ResultWas::Warning)
12743             m_messageScopes.clear();
12744 
12745         // Reset working state
12746         resetAssertionInfo();
12747         m_lastResult = result;
12748     }
resetAssertionInfo()12749     void RunContext::resetAssertionInfo() {
12750         m_lastAssertionInfo.macroName = StringRef();
12751         m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12752     }
12753 
sectionStarted(SectionInfo const & sectionInfo,Counts & assertions)12754     bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12755         ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12756         if (!sectionTracker.isOpen())
12757             return false;
12758         m_activeSections.push_back(&sectionTracker);
12759 
12760         m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12761 
12762         m_reporter->sectionStarting(sectionInfo);
12763 
12764         assertions = m_totals.assertions;
12765 
12766         return true;
12767     }
acquireGeneratorTracker(StringRef generatorName,SourceLineInfo const & lineInfo)12768     auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12769         using namespace Generators;
12770         GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12771                                                               TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12772         m_lastAssertionInfo.lineInfo = lineInfo;
12773         return tracker;
12774     }
12775 
testForMissingAssertions(Counts & assertions)12776     bool RunContext::testForMissingAssertions(Counts& assertions) {
12777         if (assertions.total() != 0)
12778             return false;
12779         if (!m_config->warnAboutMissingAssertions())
12780             return false;
12781         if (m_trackerContext.currentTracker().hasChildren())
12782             return false;
12783         m_totals.assertions.failed++;
12784         assertions.failed++;
12785         return true;
12786     }
12787 
sectionEnded(SectionEndInfo const & endInfo)12788     void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12789         Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12790         bool missingAssertions = testForMissingAssertions(assertions);
12791 
12792         if (!m_activeSections.empty()) {
12793             m_activeSections.back()->close();
12794             m_activeSections.pop_back();
12795         }
12796 
12797         m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12798         m_messages.clear();
12799         m_messageScopes.clear();
12800     }
12801 
sectionEndedEarly(SectionEndInfo const & endInfo)12802     void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12803         if (m_unfinishedSections.empty())
12804             m_activeSections.back()->fail();
12805         else
12806             m_activeSections.back()->close();
12807         m_activeSections.pop_back();
12808 
12809         m_unfinishedSections.push_back(endInfo);
12810     }
12811 
12812 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)12813     void RunContext::benchmarkPreparing(std::string const& name) {
12814         m_reporter->benchmarkPreparing(name);
12815     }
benchmarkStarting(BenchmarkInfo const & info)12816     void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12817         m_reporter->benchmarkStarting( info );
12818     }
benchmarkEnded(BenchmarkStats<> const & stats)12819     void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12820         m_reporter->benchmarkEnded( stats );
12821     }
benchmarkFailed(std::string const & error)12822     void RunContext::benchmarkFailed(std::string const & error) {
12823         m_reporter->benchmarkFailed(error);
12824     }
12825 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12826 
pushScopedMessage(MessageInfo const & message)12827     void RunContext::pushScopedMessage(MessageInfo const & message) {
12828         m_messages.push_back(message);
12829     }
12830 
popScopedMessage(MessageInfo const & message)12831     void RunContext::popScopedMessage(MessageInfo const & message) {
12832         m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12833     }
12834 
emplaceUnscopedMessage(MessageBuilder const & builder)12835     void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12836         m_messageScopes.emplace_back( builder );
12837     }
12838 
getCurrentTestName() const12839     std::string RunContext::getCurrentTestName() const {
12840         return m_activeTestCase
12841             ? m_activeTestCase->getTestCaseInfo().name
12842             : std::string();
12843     }
12844 
getLastResult() const12845     const AssertionResult * RunContext::getLastResult() const {
12846         return &(*m_lastResult);
12847     }
12848 
exceptionEarlyReported()12849     void RunContext::exceptionEarlyReported() {
12850         m_shouldReportUnexpected = false;
12851     }
12852 
handleFatalErrorCondition(StringRef message)12853     void RunContext::handleFatalErrorCondition( StringRef message ) {
12854         // First notify reporter that bad things happened
12855         m_reporter->fatalErrorEncountered(message);
12856 
12857         // Don't rebuild the result -- the stringification itself can cause more fatal errors
12858         // Instead, fake a result data.
12859         AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12860         tempResult.message = static_cast<std::string>(message);
12861         AssertionResult result(m_lastAssertionInfo, tempResult);
12862 
12863         assertionEnded(result);
12864 
12865         handleUnfinishedSections();
12866 
12867         // Recreate section for test case (as we will lose the one that was in scope)
12868         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12869         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12870 
12871         Counts assertions;
12872         assertions.failed = 1;
12873         SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12874         m_reporter->sectionEnded(testCaseSectionStats);
12875 
12876         auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12877 
12878         Totals deltaTotals;
12879         deltaTotals.testCases.failed = 1;
12880         deltaTotals.assertions.failed = 1;
12881         m_reporter->testCaseEnded(TestCaseStats(testInfo,
12882                                   deltaTotals,
12883                                   std::string(),
12884                                   std::string(),
12885                                   false));
12886         m_totals.testCases.failed++;
12887         testGroupEnded(std::string(), m_totals, 1, 1);
12888         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12889     }
12890 
lastAssertionPassed()12891     bool RunContext::lastAssertionPassed() {
12892          return m_lastAssertionPassed;
12893     }
12894 
assertionPassed()12895     void RunContext::assertionPassed() {
12896         m_lastAssertionPassed = true;
12897         ++m_totals.assertions.passed;
12898         resetAssertionInfo();
12899         m_messageScopes.clear();
12900     }
12901 
aborting() const12902     bool RunContext::aborting() const {
12903         return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12904     }
12905 
runCurrentTest(std::string & redirectedCout,std::string & redirectedCerr)12906     void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12907         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12908         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12909         m_reporter->sectionStarting(testCaseSection);
12910         Counts prevAssertions = m_totals.assertions;
12911         double duration = 0;
12912         m_shouldReportUnexpected = true;
12913         m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12914 
12915         seedRng(*m_config);
12916 
12917         Timer timer;
12918         CATCH_TRY {
12919             if (m_reporter->getPreferences().shouldRedirectStdOut) {
12920 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12921                 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12922 
12923                 timer.start();
12924                 invokeActiveTestCase();
12925 #else
12926                 OutputRedirect r(redirectedCout, redirectedCerr);
12927                 timer.start();
12928                 invokeActiveTestCase();
12929 #endif
12930             } else {
12931                 timer.start();
12932                 invokeActiveTestCase();
12933             }
12934             duration = timer.getElapsedSeconds();
12935         } CATCH_CATCH_ANON (TestFailureException&) {
12936             // This just means the test was aborted due to failure
12937         } CATCH_CATCH_ALL {
12938             // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
12939             // are reported without translation at the point of origin.
12940             if( m_shouldReportUnexpected ) {
12941                 AssertionReaction dummyReaction;
12942                 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
12943             }
12944         }
12945         Counts assertions = m_totals.assertions - prevAssertions;
12946         bool missingAssertions = testForMissingAssertions(assertions);
12947 
12948         m_testCaseTracker->close();
12949         handleUnfinishedSections();
12950         m_messages.clear();
12951         m_messageScopes.clear();
12952 
12953         SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
12954         m_reporter->sectionEnded(testCaseSectionStats);
12955     }
12956 
invokeActiveTestCase()12957     void RunContext::invokeActiveTestCase() {
12958         FatalConditionHandler fatalConditionHandler; // Handle signals
12959         m_activeTestCase->invoke();
12960         fatalConditionHandler.reset();
12961     }
12962 
handleUnfinishedSections()12963     void RunContext::handleUnfinishedSections() {
12964         // If sections ended prematurely due to an exception we stored their
12965         // infos here so we can tear them down outside the unwind process.
12966         for (auto it = m_unfinishedSections.rbegin(),
12967              itEnd = m_unfinishedSections.rend();
12968              it != itEnd;
12969              ++it)
12970             sectionEnded(*it);
12971         m_unfinishedSections.clear();
12972     }
12973 
handleExpr(AssertionInfo const & info,ITransientExpression const & expr,AssertionReaction & reaction)12974     void RunContext::handleExpr(
12975         AssertionInfo const& info,
12976         ITransientExpression const& expr,
12977         AssertionReaction& reaction
12978     ) {
12979         m_reporter->assertionStarting( info );
12980 
12981         bool negated = isFalseTest( info.resultDisposition );
12982         bool result = expr.getResult() != negated;
12983 
12984         if( result ) {
12985             if (!m_includeSuccessfulResults) {
12986                 assertionPassed();
12987             }
12988             else {
12989                 reportExpr(info, ResultWas::Ok, &expr, negated);
12990             }
12991         }
12992         else {
12993             reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
12994             populateReaction( reaction );
12995         }
12996     }
reportExpr(AssertionInfo const & info,ResultWas::OfType resultType,ITransientExpression const * expr,bool negated)12997     void RunContext::reportExpr(
12998             AssertionInfo const &info,
12999             ResultWas::OfType resultType,
13000             ITransientExpression const *expr,
13001             bool negated ) {
13002 
13003         m_lastAssertionInfo = info;
13004         AssertionResultData data( resultType, LazyExpression( negated ) );
13005 
13006         AssertionResult assertionResult{ info, data };
13007         assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13008 
13009         assertionEnded( assertionResult );
13010     }
13011 
handleMessage(AssertionInfo const & info,ResultWas::OfType resultType,StringRef const & message,AssertionReaction & reaction)13012     void RunContext::handleMessage(
13013             AssertionInfo const& info,
13014             ResultWas::OfType resultType,
13015             StringRef const& message,
13016             AssertionReaction& reaction
13017     ) {
13018         m_reporter->assertionStarting( info );
13019 
13020         m_lastAssertionInfo = info;
13021 
13022         AssertionResultData data( resultType, LazyExpression( false ) );
13023         data.message = static_cast<std::string>(message);
13024         AssertionResult assertionResult{ m_lastAssertionInfo, data };
13025         assertionEnded( assertionResult );
13026         if( !assertionResult.isOk() )
13027             populateReaction( reaction );
13028     }
handleUnexpectedExceptionNotThrown(AssertionInfo const & info,AssertionReaction & reaction)13029     void RunContext::handleUnexpectedExceptionNotThrown(
13030             AssertionInfo const& info,
13031             AssertionReaction& reaction
13032     ) {
13033         handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13034     }
13035 
handleUnexpectedInflightException(AssertionInfo const & info,std::string const & message,AssertionReaction & reaction)13036     void RunContext::handleUnexpectedInflightException(
13037             AssertionInfo const& info,
13038             std::string const& message,
13039             AssertionReaction& reaction
13040     ) {
13041         m_lastAssertionInfo = info;
13042 
13043         AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13044         data.message = message;
13045         AssertionResult assertionResult{ info, data };
13046         assertionEnded( assertionResult );
13047         populateReaction( reaction );
13048     }
13049 
populateReaction(AssertionReaction & reaction)13050     void RunContext::populateReaction( AssertionReaction& reaction ) {
13051         reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13052         reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13053     }
13054 
handleIncomplete(AssertionInfo const & info)13055     void RunContext::handleIncomplete(
13056             AssertionInfo const& info
13057     ) {
13058         m_lastAssertionInfo = info;
13059 
13060         AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13061         data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13062         AssertionResult assertionResult{ info, data };
13063         assertionEnded( assertionResult );
13064     }
handleNonExpr(AssertionInfo const & info,ResultWas::OfType resultType,AssertionReaction & reaction)13065     void RunContext::handleNonExpr(
13066             AssertionInfo const &info,
13067             ResultWas::OfType resultType,
13068             AssertionReaction &reaction
13069     ) {
13070         m_lastAssertionInfo = info;
13071 
13072         AssertionResultData data( resultType, LazyExpression( false ) );
13073         AssertionResult assertionResult{ info, data };
13074         assertionEnded( assertionResult );
13075 
13076         if( !assertionResult.isOk() )
13077             populateReaction( reaction );
13078     }
13079 
getResultCapture()13080     IResultCapture& getResultCapture() {
13081         if (auto* capture = getCurrentContext().getResultCapture())
13082             return *capture;
13083         else
13084             CATCH_INTERNAL_ERROR("No result capture instance");
13085     }
13086 
seedRng(IConfig const & config)13087     void seedRng(IConfig const& config) {
13088         if (config.rngSeed() != 0) {
13089             std::srand(config.rngSeed());
13090             rng().seed(config.rngSeed());
13091         }
13092     }
13093 
rngSeed()13094     unsigned int rngSeed() {
13095         return getCurrentContext().getConfig()->rngSeed();
13096     }
13097 
13098 }
13099 // end catch_run_context.cpp
13100 // start catch_section.cpp
13101 
13102 namespace Catch {
13103 
Section(SectionInfo const & info)13104     Section::Section( SectionInfo const& info )
13105     :   m_info( info ),
13106         m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13107     {
13108         m_timer.start();
13109     }
13110 
~Section()13111     Section::~Section() {
13112         if( m_sectionIncluded ) {
13113             SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13114             if( uncaught_exceptions() )
13115                 getResultCapture().sectionEndedEarly( endInfo );
13116             else
13117                 getResultCapture().sectionEnded( endInfo );
13118         }
13119     }
13120 
13121     // This indicates whether the section should be executed or not
operator bool() const13122     Section::operator bool() const {
13123         return m_sectionIncluded;
13124     }
13125 
13126 } // end namespace Catch
13127 // end catch_section.cpp
13128 // start catch_section_info.cpp
13129 
13130 namespace Catch {
13131 
SectionInfo(SourceLineInfo const & _lineInfo,std::string const & _name)13132     SectionInfo::SectionInfo
13133         (   SourceLineInfo const& _lineInfo,
13134             std::string const& _name )
13135     :   name( _name ),
13136         lineInfo( _lineInfo )
13137     {}
13138 
13139 } // end namespace Catch
13140 // end catch_section_info.cpp
13141 // start catch_session.cpp
13142 
13143 // start catch_session.h
13144 
13145 #include <memory>
13146 
13147 namespace Catch {
13148 
13149     class Session : NonCopyable {
13150     public:
13151 
13152         Session();
13153         ~Session() override;
13154 
13155         void showHelp() const;
13156         void libIdentify();
13157 
13158         int applyCommandLine( int argc, char const * const * argv );
13159     #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13160         int applyCommandLine( int argc, wchar_t const * const * argv );
13161     #endif
13162 
13163         void useConfigData( ConfigData const& configData );
13164 
13165         template<typename CharT>
run(int argc,CharT const * const argv[])13166         int run(int argc, CharT const * const argv[]) {
13167             if (m_startupExceptions)
13168                 return 1;
13169             int returnCode = applyCommandLine(argc, argv);
13170             if (returnCode == 0)
13171                 returnCode = run();
13172             return returnCode;
13173         }
13174 
13175         int run();
13176 
13177         clara::Parser const& cli() const;
13178         void cli( clara::Parser const& newParser );
13179         ConfigData& configData();
13180         Config& config();
13181     private:
13182         int runInternal();
13183 
13184         clara::Parser m_cli;
13185         ConfigData m_configData;
13186         std::shared_ptr<Config> m_config;
13187         bool m_startupExceptions = false;
13188     };
13189 
13190 } // end namespace Catch
13191 
13192 // end catch_session.h
13193 // start catch_version.h
13194 
13195 #include <iosfwd>
13196 
13197 namespace Catch {
13198 
13199     // Versioning information
13200     struct Version {
13201         Version( Version const& ) = delete;
13202         Version& operator=( Version const& ) = delete;
13203         Version(    unsigned int _majorVersion,
13204                     unsigned int _minorVersion,
13205                     unsigned int _patchNumber,
13206                     char const * const _branchName,
13207                     unsigned int _buildNumber );
13208 
13209         unsigned int const majorVersion;
13210         unsigned int const minorVersion;
13211         unsigned int const patchNumber;
13212 
13213         // buildNumber is only used if branchName is not null
13214         char const * const branchName;
13215         unsigned int const buildNumber;
13216 
13217         friend std::ostream& operator << ( std::ostream& os, Version const& version );
13218     };
13219 
13220     Version const& libraryVersion();
13221 }
13222 
13223 // end catch_version.h
13224 #include <cstdlib>
13225 #include <iomanip>
13226 #include <set>
13227 #include <iterator>
13228 
13229 namespace Catch {
13230 
13231     namespace {
13232         const int MaxExitCode = 255;
13233 
createReporter(std::string const & reporterName,IConfigPtr const & config)13234         IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13235             auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13236             CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13237 
13238             return reporter;
13239         }
13240 
makeReporter(std::shared_ptr<Config> const & config)13241         IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13242             if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13243                 return createReporter(config->getReporterName(), config);
13244             }
13245 
13246             // On older platforms, returning std::unique_ptr<ListeningReporter>
13247             // when the return type is std::unique_ptr<IStreamingReporter>
13248             // doesn't compile without a std::move call. However, this causes
13249             // a warning on newer platforms. Thus, we have to work around
13250             // it a bit and downcast the pointer manually.
13251             auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13252             auto& multi = static_cast<ListeningReporter&>(*ret);
13253             auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13254             for (auto const& listener : listeners) {
13255                 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13256             }
13257             multi.addReporter(createReporter(config->getReporterName(), config));
13258             return ret;
13259         }
13260 
13261         class TestGroup {
13262         public:
TestGroup(std::shared_ptr<Config> const & config)13263             explicit TestGroup(std::shared_ptr<Config> const& config)
13264             : m_config{config}
13265             , m_context{config, makeReporter(config)}
13266             {
13267                 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13268                 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13269                 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13270 
13271                 if (m_matches.empty() && invalidArgs.empty()) {
13272                     for (auto const& test : allTestCases)
13273                         if (!test.isHidden())
13274                             m_tests.emplace(&test);
13275                 } else {
13276                     for (auto const& match : m_matches)
13277                         m_tests.insert(match.tests.begin(), match.tests.end());
13278                 }
13279             }
13280 
execute()13281             Totals execute() {
13282                 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13283                 Totals totals;
13284                 m_context.testGroupStarting(m_config->name(), 1, 1);
13285                 for (auto const& testCase : m_tests) {
13286                     if (!m_context.aborting())
13287                         totals += m_context.runTest(*testCase);
13288                     else
13289                         m_context.reporter().skipTest(*testCase);
13290                 }
13291 
13292                 for (auto const& match : m_matches) {
13293                     if (match.tests.empty()) {
13294                         m_context.reporter().noMatchingTestCases(match.name);
13295                         totals.error = -1;
13296                     }
13297                 }
13298 
13299                 if (!invalidArgs.empty()) {
13300                     for (auto const& invalidArg: invalidArgs)
13301                          m_context.reporter().reportInvalidArguments(invalidArg);
13302                 }
13303 
13304                 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13305                 return totals;
13306             }
13307 
13308         private:
13309             using Tests = std::set<TestCase const*>;
13310 
13311             std::shared_ptr<Config> m_config;
13312             RunContext m_context;
13313             Tests m_tests;
13314             TestSpec::Matches m_matches;
13315         };
13316 
applyFilenamesAsTags(Catch::IConfig const & config)13317         void applyFilenamesAsTags(Catch::IConfig const& config) {
13318             auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13319             for (auto& testCase : tests) {
13320                 auto tags = testCase.tags;
13321 
13322                 std::string filename = testCase.lineInfo.file;
13323                 auto lastSlash = filename.find_last_of("\\/");
13324                 if (lastSlash != std::string::npos) {
13325                     filename.erase(0, lastSlash);
13326                     filename[0] = '#';
13327                 }
13328 
13329                 auto lastDot = filename.find_last_of('.');
13330                 if (lastDot != std::string::npos) {
13331                     filename.erase(lastDot);
13332                 }
13333 
13334                 tags.push_back(std::move(filename));
13335                 setTags(testCase, tags);
13336             }
13337         }
13338 
13339     } // anon namespace
13340 
Session()13341     Session::Session() {
13342         static bool alreadyInstantiated = false;
13343         if( alreadyInstantiated ) {
13344             CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
13345             CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13346         }
13347 
13348         // There cannot be exceptions at startup in no-exception mode.
13349 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13350         const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13351         if ( !exceptions.empty() ) {
13352             config();
13353             getCurrentMutableContext().setConfig(m_config);
13354 
13355             m_startupExceptions = true;
13356             Colour colourGuard( Colour::Red );
13357             Catch::cerr() << "Errors occurred during startup!" << '\n';
13358             // iterate over all exceptions and notify user
13359             for ( const auto& ex_ptr : exceptions ) {
13360                 try {
13361                     std::rethrow_exception(ex_ptr);
13362                 } catch ( std::exception const& ex ) {
13363                     Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
13364                 }
13365             }
13366         }
13367 #endif
13368 
13369         alreadyInstantiated = true;
13370         m_cli = makeCommandLineParser( m_configData );
13371     }
~Session()13372     Session::~Session() {
13373         Catch::cleanUp();
13374     }
13375 
showHelp() const13376     void Session::showHelp() const {
13377         Catch::cout()
13378                 << "\nCatch v" << libraryVersion() << "\n"
13379                 << m_cli << std::endl
13380                 << "For more detailed usage please see the project docs\n" << std::endl;
13381     }
libIdentify()13382     void Session::libIdentify() {
13383         Catch::cout()
13384                 << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13385                 << std::left << std::setw(16) << "category: " << "testframework\n"
13386                 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13387                 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13388     }
13389 
applyCommandLine(int argc,char const * const * argv)13390     int Session::applyCommandLine( int argc, char const * const * argv ) {
13391         if( m_startupExceptions )
13392             return 1;
13393 
13394         auto result = m_cli.parse( clara::Args( argc, argv ) );
13395         if( !result ) {
13396             config();
13397             getCurrentMutableContext().setConfig(m_config);
13398             Catch::cerr()
13399                 << Colour( Colour::Red )
13400                 << "\nError(s) in input:\n"
13401                 << Column( result.errorMessage() ).indent( 2 )
13402                 << "\n\n";
13403             Catch::cerr() << "Run with -? for usage\n" << std::endl;
13404             return MaxExitCode;
13405         }
13406 
13407         if( m_configData.showHelp )
13408             showHelp();
13409         if( m_configData.libIdentify )
13410             libIdentify();
13411         m_config.reset();
13412         return 0;
13413     }
13414 
13415 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
applyCommandLine(int argc,wchar_t const * const * argv)13416     int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
13417 
13418         char **utf8Argv = new char *[ argc ];
13419 
13420         for ( int i = 0; i < argc; ++i ) {
13421             int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
13422 
13423             utf8Argv[ i ] = new char[ bufSize ];
13424 
13425             WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
13426         }
13427 
13428         int returnCode = applyCommandLine( argc, utf8Argv );
13429 
13430         for ( int i = 0; i < argc; ++i )
13431             delete [] utf8Argv[ i ];
13432 
13433         delete [] utf8Argv;
13434 
13435         return returnCode;
13436     }
13437 #endif
13438 
useConfigData(ConfigData const & configData)13439     void Session::useConfigData( ConfigData const& configData ) {
13440         m_configData = configData;
13441         m_config.reset();
13442     }
13443 
run()13444     int Session::run() {
13445         if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13446             Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13447             static_cast<void>(std::getchar());
13448         }
13449         int exitCode = runInternal();
13450         if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13451             Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13452             static_cast<void>(std::getchar());
13453         }
13454         return exitCode;
13455     }
13456 
cli() const13457     clara::Parser const& Session::cli() const {
13458         return m_cli;
13459     }
cli(clara::Parser const & newParser)13460     void Session::cli( clara::Parser const& newParser ) {
13461         m_cli = newParser;
13462     }
configData()13463     ConfigData& Session::configData() {
13464         return m_configData;
13465     }
config()13466     Config& Session::config() {
13467         if( !m_config )
13468             m_config = std::make_shared<Config>( m_configData );
13469         return *m_config;
13470     }
13471 
runInternal()13472     int Session::runInternal() {
13473         if( m_startupExceptions )
13474             return 1;
13475 
13476         if (m_configData.showHelp || m_configData.libIdentify) {
13477             return 0;
13478         }
13479 
13480         CATCH_TRY {
13481             config(); // Force config to be constructed
13482 
13483             seedRng( *m_config );
13484 
13485             if( m_configData.filenamesAsTags )
13486                 applyFilenamesAsTags( *m_config );
13487 
13488             // Handle list request
13489             if( Option<std::size_t> listed = list( m_config ) )
13490                 return static_cast<int>( *listed );
13491 
13492             TestGroup tests { m_config };
13493             auto const totals = tests.execute();
13494 
13495             if( m_config->warnAboutNoTests() && totals.error == -1 )
13496                 return 2;
13497 
13498             // Note that on unices only the lower 8 bits are usually used, clamping
13499             // the return value to 255 prevents false negative when some multiple
13500             // of 256 tests has failed
13501             return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13502         }
13503 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13504         catch( std::exception& ex ) {
13505             Catch::cerr() << ex.what() << std::endl;
13506             return MaxExitCode;
13507         }
13508 #endif
13509     }
13510 
13511 } // end namespace Catch
13512 // end catch_session.cpp
13513 // start catch_singletons.cpp
13514 
13515 #include <vector>
13516 
13517 namespace Catch {
13518 
13519     namespace {
getSingletons()13520         static auto getSingletons() -> std::vector<ISingleton*>*& {
13521             static std::vector<ISingleton*>* g_singletons = nullptr;
13522             if( !g_singletons )
13523                 g_singletons = new std::vector<ISingleton*>();
13524             return g_singletons;
13525         }
13526     }
13527 
~ISingleton()13528     ISingleton::~ISingleton() {}
13529 
addSingleton(ISingleton * singleton)13530     void addSingleton(ISingleton* singleton ) {
13531         getSingletons()->push_back( singleton );
13532     }
cleanupSingletons()13533     void cleanupSingletons() {
13534         auto& singletons = getSingletons();
13535         for( auto singleton : *singletons )
13536             delete singleton;
13537         delete singletons;
13538         singletons = nullptr;
13539     }
13540 
13541 } // namespace Catch
13542 // end catch_singletons.cpp
13543 // start catch_startup_exception_registry.cpp
13544 
13545 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13546 namespace Catch {
add(std::exception_ptr const & exception)13547 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
13548         CATCH_TRY {
13549             m_exceptions.push_back(exception);
13550         } CATCH_CATCH_ALL {
13551             // If we run out of memory during start-up there's really not a lot more we can do about it
13552             std::terminate();
13553         }
13554     }
13555 
getExceptions() const13556     std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13557         return m_exceptions;
13558     }
13559 
13560 } // end namespace Catch
13561 #endif
13562 // end catch_startup_exception_registry.cpp
13563 // start catch_stream.cpp
13564 
13565 #include <cstdio>
13566 #include <iostream>
13567 #include <fstream>
13568 #include <sstream>
13569 #include <vector>
13570 #include <memory>
13571 
13572 namespace Catch {
13573 
13574     Catch::IStream::~IStream() = default;
13575 
13576     namespace Detail { namespace {
13577         template<typename WriterF, std::size_t bufferSize=256>
13578         class StreamBufImpl : public std::streambuf {
13579             char data[bufferSize];
13580             WriterF m_writer;
13581 
13582         public:
StreamBufImpl()13583             StreamBufImpl() {
13584                 setp( data, data + sizeof(data) );
13585             }
13586 
~StreamBufImpl()13587             ~StreamBufImpl() noexcept {
13588                 StreamBufImpl::sync();
13589             }
13590 
13591         private:
overflow(int c)13592             int overflow( int c ) override {
13593                 sync();
13594 
13595                 if( c != EOF ) {
13596                     if( pbase() == epptr() )
13597                         m_writer( std::string( 1, static_cast<char>( c ) ) );
13598                     else
13599                         sputc( static_cast<char>( c ) );
13600                 }
13601                 return 0;
13602             }
13603 
sync()13604             int sync() override {
13605                 if( pbase() != pptr() ) {
13606                     m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13607                     setp( pbase(), epptr() );
13608                 }
13609                 return 0;
13610             }
13611         };
13612 
13613         ///////////////////////////////////////////////////////////////////////////
13614 
13615         struct OutputDebugWriter {
13616 
operator ()Catch::Detail::__anon08ec97e13b11::OutputDebugWriter13617             void operator()( std::string const&str ) {
13618                 writeToDebugConsole( str );
13619             }
13620         };
13621 
13622         ///////////////////////////////////////////////////////////////////////////
13623 
13624         class FileStream : public IStream {
13625             mutable std::ofstream m_ofs;
13626         public:
FileStream(StringRef filename)13627             FileStream( StringRef filename ) {
13628                 m_ofs.open( filename.c_str() );
13629                 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13630             }
13631             ~FileStream() override = default;
13632         public: // IStream
stream() const13633             std::ostream& stream() const override {
13634                 return m_ofs;
13635             }
13636         };
13637 
13638         ///////////////////////////////////////////////////////////////////////////
13639 
13640         class CoutStream : public IStream {
13641             mutable std::ostream m_os;
13642         public:
13643             // Store the streambuf from cout up-front because
13644             // cout may get redirected when running tests
CoutStream()13645             CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13646             ~CoutStream() override = default;
13647 
13648         public: // IStream
stream() const13649             std::ostream& stream() const override { return m_os; }
13650         };
13651 
13652         ///////////////////////////////////////////////////////////////////////////
13653 
13654         class DebugOutStream : public IStream {
13655             std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13656             mutable std::ostream m_os;
13657         public:
DebugOutStream()13658             DebugOutStream()
13659             :   m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13660                 m_os( m_streamBuf.get() )
13661             {}
13662 
13663             ~DebugOutStream() override = default;
13664 
13665         public: // IStream
stream() const13666             std::ostream& stream() const override { return m_os; }
13667         };
13668 
13669     }} // namespace anon::detail
13670 
13671     ///////////////////////////////////////////////////////////////////////////
13672 
makeStream(StringRef const & filename)13673     auto makeStream( StringRef const &filename ) -> IStream const* {
13674         if( filename.empty() )
13675             return new Detail::CoutStream();
13676         else if( filename[0] == '%' ) {
13677             if( filename == "%debug" )
13678                 return new Detail::DebugOutStream();
13679             else
13680                 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13681         }
13682         else
13683             return new Detail::FileStream( filename );
13684     }
13685 
13686     // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13687     struct StringStreams {
13688         std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13689         std::vector<std::size_t> m_unused;
13690         std::ostringstream m_referenceStream; // Used for copy state/ flags from
13691 
addCatch::StringStreams13692         auto add() -> std::size_t {
13693             if( m_unused.empty() ) {
13694                 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13695                 return m_streams.size()-1;
13696             }
13697             else {
13698                 auto index = m_unused.back();
13699                 m_unused.pop_back();
13700                 return index;
13701             }
13702         }
13703 
releaseCatch::StringStreams13704         void release( std::size_t index ) {
13705             m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13706             m_unused.push_back(index);
13707         }
13708     };
13709 
ReusableStringStream()13710     ReusableStringStream::ReusableStringStream()
13711     :   m_index( Singleton<StringStreams>::getMutable().add() ),
13712         m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13713     {}
13714 
~ReusableStringStream()13715     ReusableStringStream::~ReusableStringStream() {
13716         static_cast<std::ostringstream*>( m_oss )->str("");
13717         m_oss->clear();
13718         Singleton<StringStreams>::getMutable().release( m_index );
13719     }
13720 
str() const13721     auto ReusableStringStream::str() const -> std::string {
13722         return static_cast<std::ostringstream*>( m_oss )->str();
13723     }
13724 
13725     ///////////////////////////////////////////////////////////////////////////
13726 
13727 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
cout()13728     std::ostream& cout() { return std::cout; }
cerr()13729     std::ostream& cerr() { return std::cerr; }
clog()13730     std::ostream& clog() { return std::clog; }
13731 #endif
13732 }
13733 // end catch_stream.cpp
13734 // start catch_string_manip.cpp
13735 
13736 #include <algorithm>
13737 #include <ostream>
13738 #include <cstring>
13739 #include <cctype>
13740 #include <vector>
13741 
13742 namespace Catch {
13743 
13744     namespace {
toLowerCh(char c)13745         char toLowerCh(char c) {
13746             return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13747         }
13748     }
13749 
startsWith(std::string const & s,std::string const & prefix)13750     bool startsWith( std::string const& s, std::string const& prefix ) {
13751         return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13752     }
startsWith(std::string const & s,char prefix)13753     bool startsWith( std::string const& s, char prefix ) {
13754         return !s.empty() && s[0] == prefix;
13755     }
endsWith(std::string const & s,std::string const & suffix)13756     bool endsWith( std::string const& s, std::string const& suffix ) {
13757         return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13758     }
endsWith(std::string const & s,char suffix)13759     bool endsWith( std::string const& s, char suffix ) {
13760         return !s.empty() && s[s.size()-1] == suffix;
13761     }
contains(std::string const & s,std::string const & infix)13762     bool contains( std::string const& s, std::string const& infix ) {
13763         return s.find( infix ) != std::string::npos;
13764     }
toLowerInPlace(std::string & s)13765     void toLowerInPlace( std::string& s ) {
13766         std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13767     }
toLower(std::string const & s)13768     std::string toLower( std::string const& s ) {
13769         std::string lc = s;
13770         toLowerInPlace( lc );
13771         return lc;
13772     }
trim(std::string const & str)13773     std::string trim( std::string const& str ) {
13774         static char const* whitespaceChars = "\n\r\t ";
13775         std::string::size_type start = str.find_first_not_of( whitespaceChars );
13776         std::string::size_type end = str.find_last_not_of( whitespaceChars );
13777 
13778         return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13779     }
13780 
trim(StringRef ref)13781     StringRef trim(StringRef ref) {
13782         const auto is_ws = [](char c) {
13783             return c == ' ' || c == '\t' || c == '\n' || c == '\r';
13784         };
13785         size_t real_begin = 0;
13786         while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13787         size_t real_end = ref.size();
13788         while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13789 
13790         return ref.substr(real_begin, real_end - real_begin);
13791     }
13792 
replaceInPlace(std::string & str,std::string const & replaceThis,std::string const & withThis)13793     bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13794         bool replaced = false;
13795         std::size_t i = str.find( replaceThis );
13796         while( i != std::string::npos ) {
13797             replaced = true;
13798             str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13799             if( i < str.size()-withThis.size() )
13800                 i = str.find( replaceThis, i+withThis.size() );
13801             else
13802                 i = std::string::npos;
13803         }
13804         return replaced;
13805     }
13806 
splitStringRef(StringRef str,char delimiter)13807     std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13808         std::vector<StringRef> subStrings;
13809         std::size_t start = 0;
13810         for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13811             if( str[pos] == delimiter ) {
13812                 if( pos - start > 1 )
13813                     subStrings.push_back( str.substr( start, pos-start ) );
13814                 start = pos+1;
13815             }
13816         }
13817         if( start < str.size() )
13818             subStrings.push_back( str.substr( start, str.size()-start ) );
13819         return subStrings;
13820     }
13821 
pluralise(std::size_t count,std::string const & label)13822     pluralise::pluralise( std::size_t count, std::string const& label )
13823     :   m_count( count ),
13824         m_label( label )
13825     {}
13826 
operator <<(std::ostream & os,pluralise const & pluraliser)13827     std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13828         os << pluraliser.m_count << ' ' << pluraliser.m_label;
13829         if( pluraliser.m_count != 1 )
13830             os << 's';
13831         return os;
13832     }
13833 
13834 }
13835 // end catch_string_manip.cpp
13836 // start catch_stringref.cpp
13837 
13838 #include <algorithm>
13839 #include <ostream>
13840 #include <cstring>
13841 #include <cstdint>
13842 
13843 namespace Catch {
StringRef(char const * rawChars)13844     StringRef::StringRef( char const* rawChars ) noexcept
13845     : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13846     {}
13847 
c_str() const13848     auto StringRef::c_str() const -> char const* {
13849         CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
13850         return m_start;
13851     }
data() const13852     auto StringRef::data() const noexcept -> char const* {
13853         return m_start;
13854     }
13855 
substr(size_type start,size_type size) const13856     auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13857         if (start < m_size) {
13858             return StringRef(m_start + start, (std::min)(m_size - start, size));
13859         } else {
13860             return StringRef();
13861         }
13862     }
operator ==(StringRef const & other) const13863     auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13864         return m_size == other.m_size
13865             && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13866     }
13867 
operator <<(std::ostream & os,StringRef const & str)13868     auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13869         return os.write(str.data(), str.size());
13870     }
13871 
operator +=(std::string & lhs,StringRef const & rhs)13872     auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13873         lhs.append(rhs.data(), rhs.size());
13874         return lhs;
13875     }
13876 
13877 } // namespace Catch
13878 // end catch_stringref.cpp
13879 // start catch_tag_alias.cpp
13880 
13881 namespace Catch {
TagAlias(std::string const & _tag,SourceLineInfo _lineInfo)13882     TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13883 }
13884 // end catch_tag_alias.cpp
13885 // start catch_tag_alias_autoregistrar.cpp
13886 
13887 namespace Catch {
13888 
RegistrarForTagAliases(char const * alias,char const * tag,SourceLineInfo const & lineInfo)13889     RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13890         CATCH_TRY {
13891             getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13892         } CATCH_CATCH_ALL {
13893             // Do not throw when constructing global objects, instead register the exception to be processed later
13894             getMutableRegistryHub().registerStartupException();
13895         }
13896     }
13897 
13898 }
13899 // end catch_tag_alias_autoregistrar.cpp
13900 // start catch_tag_alias_registry.cpp
13901 
13902 #include <sstream>
13903 
13904 namespace Catch {
13905 
~TagAliasRegistry()13906     TagAliasRegistry::~TagAliasRegistry() {}
13907 
find(std::string const & alias) const13908     TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13909         auto it = m_registry.find( alias );
13910         if( it != m_registry.end() )
13911             return &(it->second);
13912         else
13913             return nullptr;
13914     }
13915 
expandAliases(std::string const & unexpandedTestSpec) const13916     std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13917         std::string expandedTestSpec = unexpandedTestSpec;
13918         for( auto const& registryKvp : m_registry ) {
13919             std::size_t pos = expandedTestSpec.find( registryKvp.first );
13920             if( pos != std::string::npos ) {
13921                 expandedTestSpec =  expandedTestSpec.substr( 0, pos ) +
13922                                     registryKvp.second.tag +
13923                                     expandedTestSpec.substr( pos + registryKvp.first.size() );
13924             }
13925         }
13926         return expandedTestSpec;
13927     }
13928 
add(std::string const & alias,std::string const & tag,SourceLineInfo const & lineInfo)13929     void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
13930         CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
13931                       "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
13932 
13933         CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13934                       "error: tag alias, '" << alias << "' already registered.\n"
13935                       << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
13936                       << "\tRedefined at: " << lineInfo );
13937     }
13938 
~ITagAliasRegistry()13939     ITagAliasRegistry::~ITagAliasRegistry() {}
13940 
get()13941     ITagAliasRegistry const& ITagAliasRegistry::get() {
13942         return getRegistryHub().getTagAliasRegistry();
13943     }
13944 
13945 } // end namespace Catch
13946 // end catch_tag_alias_registry.cpp
13947 // start catch_test_case_info.cpp
13948 
13949 #include <cctype>
13950 #include <exception>
13951 #include <algorithm>
13952 #include <sstream>
13953 
13954 namespace Catch {
13955 
13956     namespace {
parseSpecialTag(std::string const & tag)13957         TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
13958             if( startsWith( tag, '.' ) ||
13959                 tag == "!hide" )
13960                 return TestCaseInfo::IsHidden;
13961             else if( tag == "!throws" )
13962                 return TestCaseInfo::Throws;
13963             else if( tag == "!shouldfail" )
13964                 return TestCaseInfo::ShouldFail;
13965             else if( tag == "!mayfail" )
13966                 return TestCaseInfo::MayFail;
13967             else if( tag == "!nonportable" )
13968                 return TestCaseInfo::NonPortable;
13969             else if( tag == "!benchmark" )
13970                 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
13971             else
13972                 return TestCaseInfo::None;
13973         }
isReservedTag(std::string const & tag)13974         bool isReservedTag( std::string const& tag ) {
13975             return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
13976         }
enforceNotReservedTag(std::string const & tag,SourceLineInfo const & _lineInfo)13977         void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
13978             CATCH_ENFORCE( !isReservedTag(tag),
13979                           "Tag name: [" << tag << "] is not allowed.\n"
13980                           << "Tag names starting with non alphanumeric characters are reserved\n"
13981                           << _lineInfo );
13982         }
13983     }
13984 
makeTestCase(ITestInvoker * _testCase,std::string const & _className,NameAndTags const & nameAndTags,SourceLineInfo const & _lineInfo)13985     TestCase makeTestCase(  ITestInvoker* _testCase,
13986                             std::string const& _className,
13987                             NameAndTags const& nameAndTags,
13988                             SourceLineInfo const& _lineInfo )
13989     {
13990         bool isHidden = false;
13991 
13992         // Parse out tags
13993         std::vector<std::string> tags;
13994         std::string desc, tag;
13995         bool inTag = false;
13996         for (char c : nameAndTags.tags) {
13997             if( !inTag ) {
13998                 if( c == '[' )
13999                     inTag = true;
14000                 else
14001                     desc += c;
14002             }
14003             else {
14004                 if( c == ']' ) {
14005                     TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14006                     if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14007                         isHidden = true;
14008                     else if( prop == TestCaseInfo::None )
14009                         enforceNotReservedTag( tag, _lineInfo );
14010 
14011                     // Merged hide tags like `[.approvals]` should be added as
14012                     // `[.][approvals]`. The `[.]` is added at later point, so
14013                     // we only strip the prefix
14014                     if (startsWith(tag, '.') && tag.size() > 1) {
14015                         tag.erase(0, 1);
14016                     }
14017                     tags.push_back( tag );
14018                     tag.clear();
14019                     inTag = false;
14020                 }
14021                 else
14022                     tag += c;
14023             }
14024         }
14025         if( isHidden ) {
14026             // Add all "hidden" tags to make them behave identically
14027             tags.insert( tags.end(), { ".", "!hide" } );
14028         }
14029 
14030         TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14031         return TestCase( _testCase, std::move(info) );
14032     }
14033 
setTags(TestCaseInfo & testCaseInfo,std::vector<std::string> tags)14034     void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14035         std::sort(begin(tags), end(tags));
14036         tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14037         testCaseInfo.lcaseTags.clear();
14038 
14039         for( auto const& tag : tags ) {
14040             std::string lcaseTag = toLower( tag );
14041             testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14042             testCaseInfo.lcaseTags.push_back( lcaseTag );
14043         }
14044         testCaseInfo.tags = std::move(tags);
14045     }
14046 
TestCaseInfo(std::string const & _name,std::string const & _className,std::string const & _description,std::vector<std::string> const & _tags,SourceLineInfo const & _lineInfo)14047     TestCaseInfo::TestCaseInfo( std::string const& _name,
14048                                 std::string const& _className,
14049                                 std::string const& _description,
14050                                 std::vector<std::string> const& _tags,
14051                                 SourceLineInfo const& _lineInfo )
14052     :   name( _name ),
14053         className( _className ),
14054         description( _description ),
14055         lineInfo( _lineInfo ),
14056         properties( None )
14057     {
14058         setTags( *this, _tags );
14059     }
14060 
isHidden() const14061     bool TestCaseInfo::isHidden() const {
14062         return ( properties & IsHidden ) != 0;
14063     }
throws() const14064     bool TestCaseInfo::throws() const {
14065         return ( properties & Throws ) != 0;
14066     }
okToFail() const14067     bool TestCaseInfo::okToFail() const {
14068         return ( properties & (ShouldFail | MayFail ) ) != 0;
14069     }
expectedToFail() const14070     bool TestCaseInfo::expectedToFail() const {
14071         return ( properties & (ShouldFail ) ) != 0;
14072     }
14073 
tagsAsString() const14074     std::string TestCaseInfo::tagsAsString() const {
14075         std::string ret;
14076         // '[' and ']' per tag
14077         std::size_t full_size = 2 * tags.size();
14078         for (const auto& tag : tags) {
14079             full_size += tag.size();
14080         }
14081         ret.reserve(full_size);
14082         for (const auto& tag : tags) {
14083             ret.push_back('[');
14084             ret.append(tag);
14085             ret.push_back(']');
14086         }
14087 
14088         return ret;
14089     }
14090 
TestCase(ITestInvoker * testCase,TestCaseInfo && info)14091     TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14092 
withName(std::string const & _newName) const14093     TestCase TestCase::withName( std::string const& _newName ) const {
14094         TestCase other( *this );
14095         other.name = _newName;
14096         return other;
14097     }
14098 
invoke() const14099     void TestCase::invoke() const {
14100         test->invoke();
14101     }
14102 
operator ==(TestCase const & other) const14103     bool TestCase::operator == ( TestCase const& other ) const {
14104         return  test.get() == other.test.get() &&
14105                 name == other.name &&
14106                 className == other.className;
14107     }
14108 
operator <(TestCase const & other) const14109     bool TestCase::operator < ( TestCase const& other ) const {
14110         return name < other.name;
14111     }
14112 
getTestCaseInfo() const14113     TestCaseInfo const& TestCase::getTestCaseInfo() const
14114     {
14115         return *this;
14116     }
14117 
14118 } // end namespace Catch
14119 // end catch_test_case_info.cpp
14120 // start catch_test_case_registry_impl.cpp
14121 
14122 #include <algorithm>
14123 #include <sstream>
14124 
14125 namespace Catch {
14126 
14127     namespace {
14128         struct TestHasher {
TestHasherCatch::__anon08ec97e13f11::TestHasher14129             explicit TestHasher(Catch::SimplePcg32& rng_instance) {
14130                 basis = rng_instance();
14131                 basis <<= 32;
14132                 basis |= rng_instance();
14133             }
14134 
14135             uint64_t basis;
14136 
operator ()Catch::__anon08ec97e13f11::TestHasher14137             uint64_t operator()(TestCase const& t) const {
14138                 // Modified FNV-1a hash
14139                 static constexpr uint64_t prime = 1099511628211;
14140                 uint64_t hash = basis;
14141                 for (const char c : t.name) {
14142                     hash ^= c;
14143                     hash *= prime;
14144                 }
14145                 return hash;
14146             }
14147         };
14148     } // end unnamed namespace
14149 
sortTests(IConfig const & config,std::vector<TestCase> const & unsortedTestCases)14150     std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
14151         switch( config.runOrder() ) {
14152             case RunTests::InDeclarationOrder:
14153                 // already in declaration order
14154                 break;
14155 
14156             case RunTests::InLexicographicalOrder: {
14157                 std::vector<TestCase> sorted = unsortedTestCases;
14158                 std::sort( sorted.begin(), sorted.end() );
14159                 return sorted;
14160             }
14161 
14162             case RunTests::InRandomOrder: {
14163                 seedRng( config );
14164                 TestHasher h( rng() );
14165 
14166                 using hashedTest = std::pair<uint64_t, TestCase const*>;
14167                 std::vector<hashedTest> indexed_tests;
14168                 indexed_tests.reserve( unsortedTestCases.size() );
14169 
14170                 for (auto const& testCase : unsortedTestCases) {
14171                     indexed_tests.emplace_back(h(testCase), &testCase);
14172                 }
14173 
14174                 std::sort(indexed_tests.begin(), indexed_tests.end(),
14175                           [](hashedTest const& lhs, hashedTest const& rhs) {
14176                           if (lhs.first == rhs.first) {
14177                               return lhs.second->name < rhs.second->name;
14178                           }
14179                           return lhs.first < rhs.first;
14180                 });
14181 
14182                 std::vector<TestCase> sorted;
14183                 sorted.reserve( indexed_tests.size() );
14184 
14185                 for (auto const& hashed : indexed_tests) {
14186                     sorted.emplace_back(*hashed.second);
14187                 }
14188 
14189                 return sorted;
14190             }
14191         }
14192         return unsortedTestCases;
14193     }
14194 
isThrowSafe(TestCase const & testCase,IConfig const & config)14195     bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
14196         return !testCase.throws() || config.allowThrows();
14197     }
14198 
matchTest(TestCase const & testCase,TestSpec const & testSpec,IConfig const & config)14199     bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
14200         return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14201     }
14202 
enforceNoDuplicateTestCases(std::vector<TestCase> const & functions)14203     void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
14204         std::set<TestCase> seenFunctions;
14205         for( auto const& function : functions ) {
14206             auto prev = seenFunctions.insert( function );
14207             CATCH_ENFORCE( prev.second,
14208                     "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14209                     << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
14210                     << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
14211         }
14212     }
14213 
filterTests(std::vector<TestCase> const & testCases,TestSpec const & testSpec,IConfig const & config)14214     std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
14215         std::vector<TestCase> filtered;
14216         filtered.reserve( testCases.size() );
14217         for (auto const& testCase : testCases) {
14218             if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14219                 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14220                 filtered.push_back(testCase);
14221             }
14222         }
14223         return filtered;
14224     }
getAllTestCasesSorted(IConfig const & config)14225     std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
14226         return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14227     }
14228 
registerTest(TestCase const & testCase)14229     void TestRegistry::registerTest( TestCase const& testCase ) {
14230         std::string name = testCase.getTestCaseInfo().name;
14231         if( name.empty() ) {
14232             ReusableStringStream rss;
14233             rss << "Anonymous test case " << ++m_unnamedCount;
14234             return registerTest( testCase.withName( rss.str() ) );
14235         }
14236         m_functions.push_back( testCase );
14237     }
14238 
getAllTests() const14239     std::vector<TestCase> const& TestRegistry::getAllTests() const {
14240         return m_functions;
14241     }
getAllTestsSorted(IConfig const & config) const14242     std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
14243         if( m_sortedFunctions.empty() )
14244             enforceNoDuplicateTestCases( m_functions );
14245 
14246         if(  m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14247             m_sortedFunctions = sortTests( config, m_functions );
14248             m_currentSortOrder = config.runOrder();
14249         }
14250         return m_sortedFunctions;
14251     }
14252 
14253     ///////////////////////////////////////////////////////////////////////////
TestInvokerAsFunction(void (* testAsFunction)())14254     TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14255 
invoke() const14256     void TestInvokerAsFunction::invoke() const {
14257         m_testAsFunction();
14258     }
14259 
extractClassName(StringRef const & classOrQualifiedMethodName)14260     std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
14261         std::string className(classOrQualifiedMethodName);
14262         if( startsWith( className, '&' ) )
14263         {
14264             std::size_t lastColons = className.rfind( "::" );
14265             std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
14266             if( penultimateColons == std::string::npos )
14267                 penultimateColons = 1;
14268             className = className.substr( penultimateColons, lastColons-penultimateColons );
14269         }
14270         return className;
14271     }
14272 
14273 } // end namespace Catch
14274 // end catch_test_case_registry_impl.cpp
14275 // start catch_test_case_tracker.cpp
14276 
14277 #include <algorithm>
14278 #include <cassert>
14279 #include <stdexcept>
14280 #include <memory>
14281 #include <sstream>
14282 
14283 #if defined(__clang__)
14284 #    pragma clang diagnostic push
14285 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
14286 #endif
14287 
14288 namespace Catch {
14289 namespace TestCaseTracking {
14290 
NameAndLocation(std::string const & _name,SourceLineInfo const & _location)14291     NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
14292     :   name( _name ),
14293         location( _location )
14294     {}
14295 
14296     ITracker::~ITracker() = default;
14297 
startRun()14298     ITracker& TrackerContext::startRun() {
14299         m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
14300         m_currentTracker = nullptr;
14301         m_runState = Executing;
14302         return *m_rootTracker;
14303     }
14304 
endRun()14305     void TrackerContext::endRun() {
14306         m_rootTracker.reset();
14307         m_currentTracker = nullptr;
14308         m_runState = NotStarted;
14309     }
14310 
startCycle()14311     void TrackerContext::startCycle() {
14312         m_currentTracker = m_rootTracker.get();
14313         m_runState = Executing;
14314     }
completeCycle()14315     void TrackerContext::completeCycle() {
14316         m_runState = CompletedCycle;
14317     }
14318 
completedCycle() const14319     bool TrackerContext::completedCycle() const {
14320         return m_runState == CompletedCycle;
14321     }
currentTracker()14322     ITracker& TrackerContext::currentTracker() {
14323         return *m_currentTracker;
14324     }
setCurrentTracker(ITracker * tracker)14325     void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14326         m_currentTracker = tracker;
14327     }
14328 
TrackerBase(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)14329     TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14330         ITracker(nameAndLocation),
14331         m_ctx( ctx ),
14332         m_parent( parent )
14333     {}
14334 
isComplete() const14335     bool TrackerBase::isComplete() const {
14336         return m_runState == CompletedSuccessfully || m_runState == Failed;
14337     }
isSuccessfullyCompleted() const14338     bool TrackerBase::isSuccessfullyCompleted() const {
14339         return m_runState == CompletedSuccessfully;
14340     }
isOpen() const14341     bool TrackerBase::isOpen() const {
14342         return m_runState != NotStarted && !isComplete();
14343     }
hasChildren() const14344     bool TrackerBase::hasChildren() const {
14345         return !m_children.empty();
14346     }
14347 
addChild(ITrackerPtr const & child)14348     void TrackerBase::addChild( ITrackerPtr const& child ) {
14349         m_children.push_back( child );
14350     }
14351 
findChild(NameAndLocation const & nameAndLocation)14352     ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
14353         auto it = std::find_if( m_children.begin(), m_children.end(),
14354             [&nameAndLocation]( ITrackerPtr const& tracker ){
14355                 return
14356                     tracker->nameAndLocation().location == nameAndLocation.location &&
14357                     tracker->nameAndLocation().name == nameAndLocation.name;
14358             } );
14359         return( it != m_children.end() )
14360             ? *it
14361             : nullptr;
14362     }
parent()14363     ITracker& TrackerBase::parent() {
14364         assert( m_parent ); // Should always be non-null except for root
14365         return *m_parent;
14366     }
14367 
openChild()14368     void TrackerBase::openChild() {
14369         if( m_runState != ExecutingChildren ) {
14370             m_runState = ExecutingChildren;
14371             if( m_parent )
14372                 m_parent->openChild();
14373         }
14374     }
14375 
isSectionTracker() const14376     bool TrackerBase::isSectionTracker() const { return false; }
isGeneratorTracker() const14377     bool TrackerBase::isGeneratorTracker() const { return false; }
14378 
open()14379     void TrackerBase::open() {
14380         m_runState = Executing;
14381         moveToThis();
14382         if( m_parent )
14383             m_parent->openChild();
14384     }
14385 
close()14386     void TrackerBase::close() {
14387 
14388         // Close any still open children (e.g. generators)
14389         while( &m_ctx.currentTracker() != this )
14390             m_ctx.currentTracker().close();
14391 
14392         switch( m_runState ) {
14393             case NeedsAnotherRun:
14394                 break;
14395 
14396             case Executing:
14397                 m_runState = CompletedSuccessfully;
14398                 break;
14399             case ExecutingChildren:
14400                 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
14401                     m_runState = CompletedSuccessfully;
14402                 break;
14403 
14404             case NotStarted:
14405             case CompletedSuccessfully:
14406             case Failed:
14407                 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
14408 
14409             default:
14410                 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
14411         }
14412         moveToParent();
14413         m_ctx.completeCycle();
14414     }
fail()14415     void TrackerBase::fail() {
14416         m_runState = Failed;
14417         if( m_parent )
14418             m_parent->markAsNeedingAnotherRun();
14419         moveToParent();
14420         m_ctx.completeCycle();
14421     }
markAsNeedingAnotherRun()14422     void TrackerBase::markAsNeedingAnotherRun() {
14423         m_runState = NeedsAnotherRun;
14424     }
14425 
moveToParent()14426     void TrackerBase::moveToParent() {
14427         assert( m_parent );
14428         m_ctx.setCurrentTracker( m_parent );
14429     }
moveToThis()14430     void TrackerBase::moveToThis() {
14431         m_ctx.setCurrentTracker( this );
14432     }
14433 
SectionTracker(NameAndLocation const & nameAndLocation,TrackerContext & ctx,ITracker * parent)14434     SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14435     :   TrackerBase( nameAndLocation, ctx, parent ),
14436         m_trimmed_name(trim(nameAndLocation.name))
14437     {
14438         if( parent ) {
14439             while( !parent->isSectionTracker() )
14440                 parent = &parent->parent();
14441 
14442             SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
14443             addNextFilters( parentSection.m_filters );
14444         }
14445     }
14446 
isComplete() const14447     bool SectionTracker::isComplete() const {
14448         bool complete = true;
14449 
14450         if (m_filters.empty()
14451             || m_filters[0] == ""
14452             || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14453             complete = TrackerBase::isComplete();
14454         }
14455         return complete;
14456     }
14457 
isSectionTracker() const14458     bool SectionTracker::isSectionTracker() const { return true; }
14459 
acquire(TrackerContext & ctx,NameAndLocation const & nameAndLocation)14460     SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
14461         std::shared_ptr<SectionTracker> section;
14462 
14463         ITracker& currentTracker = ctx.currentTracker();
14464         if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14465             assert( childTracker );
14466             assert( childTracker->isSectionTracker() );
14467             section = std::static_pointer_cast<SectionTracker>( childTracker );
14468         }
14469         else {
14470             section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
14471             currentTracker.addChild( section );
14472         }
14473         if( !ctx.completedCycle() )
14474             section->tryOpen();
14475         return *section;
14476     }
14477 
tryOpen()14478     void SectionTracker::tryOpen() {
14479         if( !isComplete() )
14480             open();
14481     }
14482 
addInitialFilters(std::vector<std::string> const & filters)14483     void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
14484         if( !filters.empty() ) {
14485             m_filters.reserve( m_filters.size() + filters.size() + 2 );
14486             m_filters.emplace_back(""); // Root - should never be consulted
14487             m_filters.emplace_back(""); // Test Case - not a section filter
14488             m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14489         }
14490     }
addNextFilters(std::vector<std::string> const & filters)14491     void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
14492         if( filters.size() > 1 )
14493             m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14494     }
14495 
getFilters() const14496     std::vector<std::string> const& SectionTracker::getFilters() const {
14497         return m_filters;
14498     }
14499 
trimmedName() const14500     std::string const& SectionTracker::trimmedName() const {
14501         return m_trimmed_name;
14502     }
14503 
14504 } // namespace TestCaseTracking
14505 
14506 using TestCaseTracking::ITracker;
14507 using TestCaseTracking::TrackerContext;
14508 using TestCaseTracking::SectionTracker;
14509 
14510 } // namespace Catch
14511 
14512 #if defined(__clang__)
14513 #    pragma clang diagnostic pop
14514 #endif
14515 // end catch_test_case_tracker.cpp
14516 // start catch_test_registry.cpp
14517 
14518 namespace Catch {
14519 
makeTestInvoker(void (* testAsFunction)())14520     auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14521         return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14522     }
14523 
NameAndTags(StringRef const & name_,StringRef const & tags_)14524     NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14525 
AutoReg(ITestInvoker * invoker,SourceLineInfo const & lineInfo,StringRef const & classOrMethod,NameAndTags const & nameAndTags)14526     AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
14527         CATCH_TRY {
14528             getMutableRegistryHub()
14529                     .registerTest(
14530                         makeTestCase(
14531                             invoker,
14532                             extractClassName( classOrMethod ),
14533                             nameAndTags,
14534                             lineInfo));
14535         } CATCH_CATCH_ALL {
14536             // Do not throw when constructing global objects, instead register the exception to be processed later
14537             getMutableRegistryHub().registerStartupException();
14538         }
14539     }
14540 
14541     AutoReg::~AutoReg() = default;
14542 }
14543 // end catch_test_registry.cpp
14544 // start catch_test_spec.cpp
14545 
14546 #include <algorithm>
14547 #include <string>
14548 #include <vector>
14549 #include <memory>
14550 
14551 namespace Catch {
14552 
Pattern(std::string const & name)14553     TestSpec::Pattern::Pattern( std::string const& name )
14554     : m_name( name )
14555     {}
14556 
14557     TestSpec::Pattern::~Pattern() = default;
14558 
name() const14559     std::string const& TestSpec::Pattern::name() const {
14560         return m_name;
14561     }
14562 
NamePattern(std::string const & name,std::string const & filterString)14563     TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14564     : Pattern( filterString )
14565     , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14566     {}
14567 
matches(TestCaseInfo const & testCase) const14568     bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14569         return m_wildcardPattern.matches( testCase.name );
14570     }
14571 
TagPattern(std::string const & tag,std::string const & filterString)14572     TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14573     : Pattern( filterString )
14574     , m_tag( toLower( tag ) )
14575     {}
14576 
matches(TestCaseInfo const & testCase) const14577     bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14578         return std::find(begin(testCase.lcaseTags),
14579                          end(testCase.lcaseTags),
14580                          m_tag) != end(testCase.lcaseTags);
14581     }
14582 
ExcludedPattern(PatternPtr const & underlyingPattern)14583     TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14584     : Pattern( underlyingPattern->name() )
14585     , m_underlyingPattern( underlyingPattern )
14586     {}
14587 
matches(TestCaseInfo const & testCase) const14588     bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14589         return !m_underlyingPattern->matches( testCase );
14590     }
14591 
matches(TestCaseInfo const & testCase) const14592     bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14593         return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14594     }
14595 
name() const14596     std::string TestSpec::Filter::name() const {
14597         std::string name;
14598         for( auto const& p : m_patterns )
14599             name += p->name();
14600         return name;
14601     }
14602 
hasFilters() const14603     bool TestSpec::hasFilters() const {
14604         return !m_filters.empty();
14605     }
14606 
matches(TestCaseInfo const & testCase) const14607     bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14608         return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14609     }
14610 
matchesByFilter(std::vector<TestCase> const & testCases,IConfig const & config) const14611     TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14612     {
14613         Matches matches( m_filters.size() );
14614         std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14615             std::vector<TestCase const*> currentMatches;
14616             for( auto const& test : testCases )
14617                 if( isThrowSafe( test, config ) && filter.matches( test ) )
14618                     currentMatches.emplace_back( &test );
14619             return FilterMatch{ filter.name(), currentMatches };
14620         } );
14621         return matches;
14622     }
14623 
getInvalidArgs() const14624     const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
14625         return  (m_invalidArgs);
14626     }
14627 
14628 }
14629 // end catch_test_spec.cpp
14630 // start catch_test_spec_parser.cpp
14631 
14632 namespace Catch {
14633 
TestSpecParser(ITagAliasRegistry const & tagAliases)14634     TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14635 
parse(std::string const & arg)14636     TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14637         m_mode = None;
14638         m_exclusion = false;
14639         m_arg = m_tagAliases->expandAliases( arg );
14640         m_escapeChars.clear();
14641         m_substring.reserve(m_arg.size());
14642         m_patternName.reserve(m_arg.size());
14643         m_realPatternPos = 0;
14644 
14645         for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14646           //if visitChar fails
14647            if( !visitChar( m_arg[m_pos] ) ){
14648                m_testSpec.m_invalidArgs.push_back(arg);
14649                break;
14650            }
14651         endMode();
14652         return *this;
14653     }
testSpec()14654     TestSpec TestSpecParser::testSpec() {
14655         addFilter();
14656         return m_testSpec;
14657     }
visitChar(char c)14658     bool TestSpecParser::visitChar( char c ) {
14659         if( (m_mode != EscapedName) && (c == '\\') ) {
14660             escape();
14661             addCharToPattern(c);
14662             return true;
14663         }else if((m_mode != EscapedName) && (c == ',') )  {
14664             return separate();
14665         }
14666 
14667         switch( m_mode ) {
14668         case None:
14669             if( processNoneChar( c ) )
14670                 return true;
14671             break;
14672         case Name:
14673             processNameChar( c );
14674             break;
14675         case EscapedName:
14676             endMode();
14677             addCharToPattern(c);
14678             return true;
14679         default:
14680         case Tag:
14681         case QuotedName:
14682             if( processOtherChar( c ) )
14683                 return true;
14684             break;
14685         }
14686 
14687         m_substring += c;
14688         if( !isControlChar( c ) ) {
14689             m_patternName += c;
14690             m_realPatternPos++;
14691         }
14692         return true;
14693     }
14694     // Two of the processing methods return true to signal the caller to return
14695     // without adding the given character to the current pattern strings
processNoneChar(char c)14696     bool TestSpecParser::processNoneChar( char c ) {
14697         switch( c ) {
14698         case ' ':
14699             return true;
14700         case '~':
14701             m_exclusion = true;
14702             return false;
14703         case '[':
14704             startNewMode( Tag );
14705             return false;
14706         case '"':
14707             startNewMode( QuotedName );
14708             return false;
14709         default:
14710             startNewMode( Name );
14711             return false;
14712         }
14713     }
processNameChar(char c)14714     void TestSpecParser::processNameChar( char c ) {
14715         if( c == '[' ) {
14716             if( m_substring == "exclude:" )
14717                 m_exclusion = true;
14718             else
14719                 endMode();
14720             startNewMode( Tag );
14721         }
14722     }
processOtherChar(char c)14723     bool TestSpecParser::processOtherChar( char c ) {
14724         if( !isControlChar( c ) )
14725             return false;
14726         m_substring += c;
14727         endMode();
14728         return true;
14729     }
startNewMode(Mode mode)14730     void TestSpecParser::startNewMode( Mode mode ) {
14731         m_mode = mode;
14732     }
endMode()14733     void TestSpecParser::endMode() {
14734         switch( m_mode ) {
14735         case Name:
14736         case QuotedName:
14737             return addNamePattern();
14738         case Tag:
14739             return addTagPattern();
14740         case EscapedName:
14741             revertBackToLastMode();
14742             return;
14743         case None:
14744         default:
14745             return startNewMode( None );
14746         }
14747     }
escape()14748     void TestSpecParser::escape() {
14749         saveLastMode();
14750         m_mode = EscapedName;
14751         m_escapeChars.push_back(m_realPatternPos);
14752     }
isControlChar(char c) const14753     bool TestSpecParser::isControlChar( char c ) const {
14754         switch( m_mode ) {
14755             default:
14756                 return false;
14757             case None:
14758                 return c == '~';
14759             case Name:
14760                 return c == '[';
14761             case EscapedName:
14762                 return true;
14763             case QuotedName:
14764                 return c == '"';
14765             case Tag:
14766                 return c == '[' || c == ']';
14767         }
14768     }
14769 
addFilter()14770     void TestSpecParser::addFilter() {
14771         if( !m_currentFilter.m_patterns.empty() ) {
14772             m_testSpec.m_filters.push_back( m_currentFilter );
14773             m_currentFilter = TestSpec::Filter();
14774         }
14775     }
14776 
saveLastMode()14777     void TestSpecParser::saveLastMode() {
14778       lastMode = m_mode;
14779     }
14780 
revertBackToLastMode()14781     void TestSpecParser::revertBackToLastMode() {
14782       m_mode = lastMode;
14783     }
14784 
separate()14785     bool TestSpecParser::separate() {
14786       if( (m_mode==QuotedName) || (m_mode==Tag) ){
14787          //invalid argument, signal failure to previous scope.
14788          m_mode = None;
14789          m_pos = m_arg.size();
14790          m_substring.clear();
14791          m_patternName.clear();
14792          m_realPatternPos = 0;
14793          return false;
14794       }
14795       endMode();
14796       addFilter();
14797       return true; //success
14798     }
14799 
preprocessPattern()14800     std::string TestSpecParser::preprocessPattern() {
14801         std::string token = m_patternName;
14802         for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14803             token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14804         m_escapeChars.clear();
14805         if (startsWith(token, "exclude:")) {
14806             m_exclusion = true;
14807             token = token.substr(8);
14808         }
14809 
14810         m_patternName.clear();
14811         m_realPatternPos = 0;
14812 
14813         return token;
14814     }
14815 
addNamePattern()14816     void TestSpecParser::addNamePattern() {
14817         auto token = preprocessPattern();
14818 
14819         if (!token.empty()) {
14820             TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14821             if (m_exclusion)
14822                 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14823             m_currentFilter.m_patterns.push_back(pattern);
14824         }
14825         m_substring.clear();
14826         m_exclusion = false;
14827         m_mode = None;
14828     }
14829 
addTagPattern()14830     void TestSpecParser::addTagPattern() {
14831         auto token = preprocessPattern();
14832 
14833         if (!token.empty()) {
14834             // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14835             // we have to create a separate hide tag and shorten the real one
14836             if (token.size() > 1 && token[0] == '.') {
14837                 token.erase(token.begin());
14838                 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14839                 if (m_exclusion) {
14840                     pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14841                 }
14842                 m_currentFilter.m_patterns.push_back(pattern);
14843             }
14844 
14845             TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14846 
14847             if (m_exclusion) {
14848                 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14849             }
14850             m_currentFilter.m_patterns.push_back(pattern);
14851         }
14852         m_substring.clear();
14853         m_exclusion = false;
14854         m_mode = None;
14855     }
14856 
parseTestSpec(std::string const & arg)14857     TestSpec parseTestSpec( std::string const& arg ) {
14858         return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14859     }
14860 
14861 } // namespace Catch
14862 // end catch_test_spec_parser.cpp
14863 // start catch_timer.cpp
14864 
14865 #include <chrono>
14866 
14867 static const uint64_t nanosecondsInSecond = 1000000000;
14868 
14869 namespace Catch {
14870 
getCurrentNanosecondsSinceEpoch()14871     auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14872         return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14873     }
14874 
14875     namespace {
estimateClockResolution()14876         auto estimateClockResolution() -> uint64_t {
14877             uint64_t sum = 0;
14878             static const uint64_t iterations = 1000000;
14879 
14880             auto startTime = getCurrentNanosecondsSinceEpoch();
14881 
14882             for( std::size_t i = 0; i < iterations; ++i ) {
14883 
14884                 uint64_t ticks;
14885                 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14886                 do {
14887                     ticks = getCurrentNanosecondsSinceEpoch();
14888                 } while( ticks == baseTicks );
14889 
14890                 auto delta = ticks - baseTicks;
14891                 sum += delta;
14892 
14893                 // If we have been calibrating for over 3 seconds -- the clock
14894                 // is terrible and we should move on.
14895                 // TBD: How to signal that the measured resolution is probably wrong?
14896                 if (ticks > startTime + 3 * nanosecondsInSecond) {
14897                     return sum / ( i + 1u );
14898                 }
14899             }
14900 
14901             // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14902             // - and potentially do more iterations if there's a high variance.
14903             return sum/iterations;
14904         }
14905     }
getEstimatedClockResolution()14906     auto getEstimatedClockResolution() -> uint64_t {
14907         static auto s_resolution = estimateClockResolution();
14908         return s_resolution;
14909     }
14910 
start()14911     void Timer::start() {
14912        m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14913     }
getElapsedNanoseconds() const14914     auto Timer::getElapsedNanoseconds() const -> uint64_t {
14915         return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14916     }
getElapsedMicroseconds() const14917     auto Timer::getElapsedMicroseconds() const -> uint64_t {
14918         return getElapsedNanoseconds()/1000;
14919     }
getElapsedMilliseconds() const14920     auto Timer::getElapsedMilliseconds() const -> unsigned int {
14921         return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14922     }
getElapsedSeconds() const14923     auto Timer::getElapsedSeconds() const -> double {
14924         return getElapsedMicroseconds()/1000000.0;
14925     }
14926 
14927 } // namespace Catch
14928 // end catch_timer.cpp
14929 // start catch_tostring.cpp
14930 
14931 #if defined(__clang__)
14932 #    pragma clang diagnostic push
14933 #    pragma clang diagnostic ignored "-Wexit-time-destructors"
14934 #    pragma clang diagnostic ignored "-Wglobal-constructors"
14935 #endif
14936 
14937 // Enable specific decls locally
14938 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14939 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
14940 #endif
14941 
14942 #include <cmath>
14943 #include <iomanip>
14944 
14945 namespace Catch {
14946 
14947 namespace Detail {
14948 
14949     const std::string unprintableString = "{?}";
14950 
14951     namespace {
14952         const int hexThreshold = 255;
14953 
14954         struct Endianness {
14955             enum Arch { Big, Little };
14956 
whichCatch::Detail::__anon08ec97e14711::Endianness14957             static Arch which() {
14958                 int one = 1;
14959                 // If the lowest byte we read is non-zero, we can assume
14960                 // that little endian format is used.
14961                 auto value = *reinterpret_cast<char*>(&one);
14962                 return value ? Little : Big;
14963             }
14964         };
14965     }
14966 
rawMemoryToString(const void * object,std::size_t size)14967     std::string rawMemoryToString( const void *object, std::size_t size ) {
14968         // Reverse order for little endian architectures
14969         int i = 0, end = static_cast<int>( size ), inc = 1;
14970         if( Endianness::which() == Endianness::Little ) {
14971             i = end-1;
14972             end = inc = -1;
14973         }
14974 
14975         unsigned char const *bytes = static_cast<unsigned char const *>(object);
14976         ReusableStringStream rss;
14977         rss << "0x" << std::setfill('0') << std::hex;
14978         for( ; i != end; i += inc )
14979              rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
14980        return rss.str();
14981     }
14982 }
14983 
14984 template<typename T>
fpToString(T value,int precision)14985 std::string fpToString( T value, int precision ) {
14986     if (Catch::isnan(value)) {
14987         return "nan";
14988     }
14989 
14990     ReusableStringStream rss;
14991     rss << std::setprecision( precision )
14992         << std::fixed
14993         << value;
14994     std::string d = rss.str();
14995     std::size_t i = d.find_last_not_of( '0' );
14996     if( i != std::string::npos && i != d.size()-1 ) {
14997         if( d[i] == '.' )
14998             i++;
14999         d = d.substr( 0, i+1 );
15000     }
15001     return d;
15002 }
15003 
15004 //// ======================================================= ////
15005 //
15006 //   Out-of-line defs for full specialization of StringMaker
15007 //
15008 //// ======================================================= ////
15009 
convert(const std::string & str)15010 std::string StringMaker<std::string>::convert(const std::string& str) {
15011     if (!getCurrentContext().getConfig()->showInvisibles()) {
15012         return '"' + str + '"';
15013     }
15014 
15015     std::string s("\"");
15016     for (char c : str) {
15017         switch (c) {
15018         case '\n':
15019             s.append("\\n");
15020             break;
15021         case '\t':
15022             s.append("\\t");
15023             break;
15024         default:
15025             s.push_back(c);
15026             break;
15027         }
15028     }
15029     s.append("\"");
15030     return s;
15031 }
15032 
15033 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::string_view str)15034 std::string StringMaker<std::string_view>::convert(std::string_view str) {
15035     return ::Catch::Detail::stringify(std::string{ str });
15036 }
15037 #endif
15038 
convert(char const * str)15039 std::string StringMaker<char const*>::convert(char const* str) {
15040     if (str) {
15041         return ::Catch::Detail::stringify(std::string{ str });
15042     } else {
15043         return{ "{null string}" };
15044     }
15045 }
convert(char * str)15046 std::string StringMaker<char*>::convert(char* str) {
15047     if (str) {
15048         return ::Catch::Detail::stringify(std::string{ str });
15049     } else {
15050         return{ "{null string}" };
15051     }
15052 }
15053 
15054 #ifdef CATCH_CONFIG_WCHAR
convert(const std::wstring & wstr)15055 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15056     std::string s;
15057     s.reserve(wstr.size());
15058     for (auto c : wstr) {
15059         s += (c <= 0xff) ? static_cast<char>(c) : '?';
15060     }
15061     return ::Catch::Detail::stringify(s);
15062 }
15063 
15064 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
convert(std::wstring_view str)15065 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15066     return StringMaker<std::wstring>::convert(std::wstring(str));
15067 }
15068 # endif
15069 
convert(wchar_t const * str)15070 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
15071     if (str) {
15072         return ::Catch::Detail::stringify(std::wstring{ str });
15073     } else {
15074         return{ "{null string}" };
15075     }
15076 }
convert(wchar_t * str)15077 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
15078     if (str) {
15079         return ::Catch::Detail::stringify(std::wstring{ str });
15080     } else {
15081         return{ "{null string}" };
15082     }
15083 }
15084 #endif
15085 
15086 #if defined(CATCH_CONFIG_CPP17_BYTE)
15087 #include <cstddef>
convert(std::byte value)15088 std::string StringMaker<std::byte>::convert(std::byte value) {
15089     return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15090 }
15091 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15092 
convert(int value)15093 std::string StringMaker<int>::convert(int value) {
15094     return ::Catch::Detail::stringify(static_cast<long long>(value));
15095 }
convert(long value)15096 std::string StringMaker<long>::convert(long value) {
15097     return ::Catch::Detail::stringify(static_cast<long long>(value));
15098 }
convert(long long value)15099 std::string StringMaker<long long>::convert(long long value) {
15100     ReusableStringStream rss;
15101     rss << value;
15102     if (value > Detail::hexThreshold) {
15103         rss << " (0x" << std::hex << value << ')';
15104     }
15105     return rss.str();
15106 }
15107 
convert(unsigned int value)15108 std::string StringMaker<unsigned int>::convert(unsigned int value) {
15109     return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15110 }
convert(unsigned long value)15111 std::string StringMaker<unsigned long>::convert(unsigned long value) {
15112     return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15113 }
convert(unsigned long long value)15114 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15115     ReusableStringStream rss;
15116     rss << value;
15117     if (value > Detail::hexThreshold) {
15118         rss << " (0x" << std::hex << value << ')';
15119     }
15120     return rss.str();
15121 }
15122 
convert(bool b)15123 std::string StringMaker<bool>::convert(bool b) {
15124     return b ? "true" : "false";
15125 }
15126 
convert(signed char value)15127 std::string StringMaker<signed char>::convert(signed char value) {
15128     if (value == '\r') {
15129         return "'\\r'";
15130     } else if (value == '\f') {
15131         return "'\\f'";
15132     } else if (value == '\n') {
15133         return "'\\n'";
15134     } else if (value == '\t') {
15135         return "'\\t'";
15136     } else if ('\0' <= value && value < ' ') {
15137         return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15138     } else {
15139         char chstr[] = "' '";
15140         chstr[1] = value;
15141         return chstr;
15142     }
15143 }
convert(char c)15144 std::string StringMaker<char>::convert(char c) {
15145     return ::Catch::Detail::stringify(static_cast<signed char>(c));
15146 }
convert(unsigned char c)15147 std::string StringMaker<unsigned char>::convert(unsigned char c) {
15148     return ::Catch::Detail::stringify(static_cast<char>(c));
15149 }
15150 
convert(std::nullptr_t)15151 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15152     return "nullptr";
15153 }
15154 
15155 int StringMaker<float>::precision = 5;
15156 
convert(float value)15157 std::string StringMaker<float>::convert(float value) {
15158     return fpToString(value, precision) + 'f';
15159 }
15160 
15161 int StringMaker<double>::precision = 10;
15162 
convert(double value)15163 std::string StringMaker<double>::convert(double value) {
15164     return fpToString(value, precision);
15165 }
15166 
symbol()15167 std::string ratio_string<std::atto>::symbol() { return "a"; }
symbol()15168 std::string ratio_string<std::femto>::symbol() { return "f"; }
symbol()15169 std::string ratio_string<std::pico>::symbol() { return "p"; }
symbol()15170 std::string ratio_string<std::nano>::symbol() { return "n"; }
symbol()15171 std::string ratio_string<std::micro>::symbol() { return "u"; }
symbol()15172 std::string ratio_string<std::milli>::symbol() { return "m"; }
15173 
15174 } // end namespace Catch
15175 
15176 #if defined(__clang__)
15177 #    pragma clang diagnostic pop
15178 #endif
15179 
15180 // end catch_tostring.cpp
15181 // start catch_totals.cpp
15182 
15183 namespace Catch {
15184 
operator -(Counts const & other) const15185     Counts Counts::operator - ( Counts const& other ) const {
15186         Counts diff;
15187         diff.passed = passed - other.passed;
15188         diff.failed = failed - other.failed;
15189         diff.failedButOk = failedButOk - other.failedButOk;
15190         return diff;
15191     }
15192 
operator +=(Counts const & other)15193     Counts& Counts::operator += ( Counts const& other ) {
15194         passed += other.passed;
15195         failed += other.failed;
15196         failedButOk += other.failedButOk;
15197         return *this;
15198     }
15199 
total() const15200     std::size_t Counts::total() const {
15201         return passed + failed + failedButOk;
15202     }
allPassed() const15203     bool Counts::allPassed() const {
15204         return failed == 0 && failedButOk == 0;
15205     }
allOk() const15206     bool Counts::allOk() const {
15207         return failed == 0;
15208     }
15209 
operator -(Totals const & other) const15210     Totals Totals::operator - ( Totals const& other ) const {
15211         Totals diff;
15212         diff.assertions = assertions - other.assertions;
15213         diff.testCases = testCases - other.testCases;
15214         return diff;
15215     }
15216 
operator +=(Totals const & other)15217     Totals& Totals::operator += ( Totals const& other ) {
15218         assertions += other.assertions;
15219         testCases += other.testCases;
15220         return *this;
15221     }
15222 
delta(Totals const & prevTotals) const15223     Totals Totals::delta( Totals const& prevTotals ) const {
15224         Totals diff = *this - prevTotals;
15225         if( diff.assertions.failed > 0 )
15226             ++diff.testCases.failed;
15227         else if( diff.assertions.failedButOk > 0 )
15228             ++diff.testCases.failedButOk;
15229         else
15230             ++diff.testCases.passed;
15231         return diff;
15232     }
15233 
15234 }
15235 // end catch_totals.cpp
15236 // start catch_uncaught_exceptions.cpp
15237 
15238 // start catch_config_uncaught_exceptions.hpp
15239 
15240 //              Copyright Catch2 Authors
15241 // Distributed under the Boost Software License, Version 1.0.
15242 //   (See accompanying file LICENSE_1_0.txt or copy at
15243 //        https://www.boost.org/LICENSE_1_0.txt)
15244 
15245 // SPDX-License-Identifier: BSL-1.0
15246 
15247 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15248 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15249 
15250 #if defined(_MSC_VER)
15251 #  if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15252 #    define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15253 #  endif
15254 #endif
15255 
15256 #include <exception>
15257 
15258 #if defined(__cpp_lib_uncaught_exceptions) \
15259     && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15260 
15261 #  define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15262 #endif // __cpp_lib_uncaught_exceptions
15263 
15264 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15265     && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15266     && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15267 
15268 #  define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15269 #endif
15270 
15271 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15272 // end catch_config_uncaught_exceptions.hpp
15273 #include <exception>
15274 
15275 namespace Catch {
uncaught_exceptions()15276     bool uncaught_exceptions() {
15277 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15278         return false;
15279 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15280         return std::uncaught_exceptions() > 0;
15281 #else
15282         return std::uncaught_exception();
15283 #endif
15284   }
15285 } // end namespace Catch
15286 // end catch_uncaught_exceptions.cpp
15287 // start catch_version.cpp
15288 
15289 #include <ostream>
15290 
15291 namespace Catch {
15292 
Version(unsigned int _majorVersion,unsigned int _minorVersion,unsigned int _patchNumber,char const * const _branchName,unsigned int _buildNumber)15293     Version::Version
15294         (   unsigned int _majorVersion,
15295             unsigned int _minorVersion,
15296             unsigned int _patchNumber,
15297             char const * const _branchName,
15298             unsigned int _buildNumber )
15299     :   majorVersion( _majorVersion ),
15300         minorVersion( _minorVersion ),
15301         patchNumber( _patchNumber ),
15302         branchName( _branchName ),
15303         buildNumber( _buildNumber )
15304     {}
15305 
operator <<(std::ostream & os,Version const & version)15306     std::ostream& operator << ( std::ostream& os, Version const& version ) {
15307         os  << version.majorVersion << '.'
15308             << version.minorVersion << '.'
15309             << version.patchNumber;
15310         // branchName is never null -> 0th char is \0 if it is empty
15311         if (version.branchName[0]) {
15312             os << '-' << version.branchName
15313                << '.' << version.buildNumber;
15314         }
15315         return os;
15316     }
15317 
libraryVersion()15318     Version const& libraryVersion() {
15319         static Version version( 2, 13, 3, "", 0 );
15320         return version;
15321     }
15322 
15323 }
15324 // end catch_version.cpp
15325 // start catch_wildcard_pattern.cpp
15326 
15327 namespace Catch {
15328 
WildcardPattern(std::string const & pattern,CaseSensitive::Choice caseSensitivity)15329     WildcardPattern::WildcardPattern( std::string const& pattern,
15330                                       CaseSensitive::Choice caseSensitivity )
15331     :   m_caseSensitivity( caseSensitivity ),
15332         m_pattern( normaliseString( pattern ) )
15333     {
15334         if( startsWith( m_pattern, '*' ) ) {
15335             m_pattern = m_pattern.substr( 1 );
15336             m_wildcard = WildcardAtStart;
15337         }
15338         if( endsWith( m_pattern, '*' ) ) {
15339             m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15340             m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
15341         }
15342     }
15343 
matches(std::string const & str) const15344     bool WildcardPattern::matches( std::string const& str ) const {
15345         switch( m_wildcard ) {
15346             case NoWildcard:
15347                 return m_pattern == normaliseString( str );
15348             case WildcardAtStart:
15349                 return endsWith( normaliseString( str ), m_pattern );
15350             case WildcardAtEnd:
15351                 return startsWith( normaliseString( str ), m_pattern );
15352             case WildcardAtBothEnds:
15353                 return contains( normaliseString( str ), m_pattern );
15354             default:
15355                 CATCH_INTERNAL_ERROR( "Unknown enum" );
15356         }
15357     }
15358 
normaliseString(std::string const & str) const15359     std::string WildcardPattern::normaliseString( std::string const& str ) const {
15360         return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15361     }
15362 }
15363 // end catch_wildcard_pattern.cpp
15364 // start catch_xmlwriter.cpp
15365 
15366 #include <iomanip>
15367 #include <type_traits>
15368 
15369 namespace Catch {
15370 
15371 namespace {
15372 
trailingBytes(unsigned char c)15373     size_t trailingBytes(unsigned char c) {
15374         if ((c & 0xE0) == 0xC0) {
15375             return 2;
15376         }
15377         if ((c & 0xF0) == 0xE0) {
15378             return 3;
15379         }
15380         if ((c & 0xF8) == 0xF0) {
15381             return 4;
15382         }
15383         CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15384     }
15385 
headerValue(unsigned char c)15386     uint32_t headerValue(unsigned char c) {
15387         if ((c & 0xE0) == 0xC0) {
15388             return c & 0x1F;
15389         }
15390         if ((c & 0xF0) == 0xE0) {
15391             return c & 0x0F;
15392         }
15393         if ((c & 0xF8) == 0xF0) {
15394             return c & 0x07;
15395         }
15396         CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15397     }
15398 
hexEscapeChar(std::ostream & os,unsigned char c)15399     void hexEscapeChar(std::ostream& os, unsigned char c) {
15400         std::ios_base::fmtflags f(os.flags());
15401         os << "\\x"
15402             << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15403             << static_cast<int>(c);
15404         os.flags(f);
15405     }
15406 
shouldNewline(XmlFormatting fmt)15407     bool shouldNewline(XmlFormatting fmt) {
15408         return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15409     }
15410 
shouldIndent(XmlFormatting fmt)15411     bool shouldIndent(XmlFormatting fmt) {
15412         return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15413     }
15414 
15415 } // anonymous namespace
15416 
operator |(XmlFormatting lhs,XmlFormatting rhs)15417     XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15418         return static_cast<XmlFormatting>(
15419             static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15420             static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15421         );
15422     }
15423 
operator &(XmlFormatting lhs,XmlFormatting rhs)15424     XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15425         return static_cast<XmlFormatting>(
15426             static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15427             static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15428         );
15429     }
15430 
XmlEncode(std::string const & str,ForWhat forWhat)15431     XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
15432     :   m_str( str ),
15433         m_forWhat( forWhat )
15434     {}
15435 
encodeTo(std::ostream & os) const15436     void XmlEncode::encodeTo( std::ostream& os ) const {
15437         // Apostrophe escaping not necessary if we always use " to write attributes
15438         // (see: http://www.w3.org/TR/xml/#syntax)
15439 
15440         for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15441             unsigned char c = m_str[idx];
15442             switch (c) {
15443             case '<':   os << "&lt;"; break;
15444             case '&':   os << "&amp;"; break;
15445 
15446             case '>':
15447                 // See: http://www.w3.org/TR/xml/#syntax
15448                 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15449                     os << "&gt;";
15450                 else
15451                     os << c;
15452                 break;
15453 
15454             case '\"':
15455                 if (m_forWhat == ForAttributes)
15456                     os << "&quot;";
15457                 else
15458                     os << c;
15459                 break;
15460 
15461             default:
15462                 // Check for control characters and invalid utf-8
15463 
15464                 // Escape control characters in standard ascii
15465                 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15466                 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15467                     hexEscapeChar(os, c);
15468                     break;
15469                 }
15470 
15471                 // Plain ASCII: Write it to stream
15472                 if (c < 0x7F) {
15473                     os << c;
15474                     break;
15475                 }
15476 
15477                 // UTF-8 territory
15478                 // Check if the encoding is valid and if it is not, hex escape bytes.
15479                 // Important: We do not check the exact decoded values for validity, only the encoding format
15480                 // First check that this bytes is a valid lead byte:
15481                 // This means that it is not encoded as 1111 1XXX
15482                 // Or as 10XX XXXX
15483                 if (c <  0xC0 ||
15484                     c >= 0xF8) {
15485                     hexEscapeChar(os, c);
15486                     break;
15487                 }
15488 
15489                 auto encBytes = trailingBytes(c);
15490                 // Are there enough bytes left to avoid accessing out-of-bounds memory?
15491                 if (idx + encBytes - 1 >= m_str.size()) {
15492                     hexEscapeChar(os, c);
15493                     break;
15494                 }
15495                 // The header is valid, check data
15496                 // The next encBytes bytes must together be a valid utf-8
15497                 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15498                 bool valid = true;
15499                 uint32_t value = headerValue(c);
15500                 for (std::size_t n = 1; n < encBytes; ++n) {
15501                     unsigned char nc = m_str[idx + n];
15502                     valid &= ((nc & 0xC0) == 0x80);
15503                     value = (value << 6) | (nc & 0x3F);
15504                 }
15505 
15506                 if (
15507                     // Wrong bit pattern of following bytes
15508                     (!valid) ||
15509                     // Overlong encodings
15510                     (value < 0x80) ||
15511                     (0x80 <= value && value < 0x800   && encBytes > 2) ||
15512                     (0x800 < value && value < 0x10000 && encBytes > 3) ||
15513                     // Encoded value out of range
15514                     (value >= 0x110000)
15515                     ) {
15516                     hexEscapeChar(os, c);
15517                     break;
15518                 }
15519 
15520                 // If we got here, this is in fact a valid(ish) utf-8 sequence
15521                 for (std::size_t n = 0; n < encBytes; ++n) {
15522                     os << m_str[idx + n];
15523                 }
15524                 idx += encBytes - 1;
15525                 break;
15526             }
15527         }
15528     }
15529 
operator <<(std::ostream & os,XmlEncode const & xmlEncode)15530     std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
15531         xmlEncode.encodeTo( os );
15532         return os;
15533     }
15534 
ScopedElement(XmlWriter * writer,XmlFormatting fmt)15535     XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15536     :   m_writer( writer ),
15537         m_fmt(fmt)
15538     {}
15539 
ScopedElement(ScopedElement && other)15540     XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15541     :   m_writer( other.m_writer ),
15542         m_fmt(other.m_fmt)
15543     {
15544         other.m_writer = nullptr;
15545         other.m_fmt = XmlFormatting::None;
15546     }
operator =(ScopedElement && other)15547     XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15548         if ( m_writer ) {
15549             m_writer->endElement();
15550         }
15551         m_writer = other.m_writer;
15552         other.m_writer = nullptr;
15553         m_fmt = other.m_fmt;
15554         other.m_fmt = XmlFormatting::None;
15555         return *this;
15556     }
15557 
~ScopedElement()15558     XmlWriter::ScopedElement::~ScopedElement() {
15559         if (m_writer) {
15560             m_writer->endElement(m_fmt);
15561         }
15562     }
15563 
writeText(std::string const & text,XmlFormatting fmt)15564     XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
15565         m_writer->writeText( text, fmt );
15566         return *this;
15567     }
15568 
XmlWriter(std::ostream & os)15569     XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15570     {
15571         writeDeclaration();
15572     }
15573 
~XmlWriter()15574     XmlWriter::~XmlWriter() {
15575         while (!m_tags.empty()) {
15576             endElement();
15577         }
15578         newlineIfNecessary();
15579     }
15580 
startElement(std::string const & name,XmlFormatting fmt)15581     XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
15582         ensureTagClosed();
15583         newlineIfNecessary();
15584         if (shouldIndent(fmt)) {
15585             m_os << m_indent;
15586             m_indent += "  ";
15587         }
15588         m_os << '<' << name;
15589         m_tags.push_back( name );
15590         m_tagIsOpen = true;
15591         applyFormatting(fmt);
15592         return *this;
15593     }
15594 
scopedElement(std::string const & name,XmlFormatting fmt)15595     XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
15596         ScopedElement scoped( this, fmt );
15597         startElement( name, fmt );
15598         return scoped;
15599     }
15600 
endElement(XmlFormatting fmt)15601     XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15602         m_indent = m_indent.substr(0, m_indent.size() - 2);
15603 
15604         if( m_tagIsOpen ) {
15605             m_os << "/>";
15606             m_tagIsOpen = false;
15607         } else {
15608             newlineIfNecessary();
15609             if (shouldIndent(fmt)) {
15610                 m_os << m_indent;
15611             }
15612             m_os << "</" << m_tags.back() << ">";
15613         }
15614         m_os << std::flush;
15615         applyFormatting(fmt);
15616         m_tags.pop_back();
15617         return *this;
15618     }
15619 
writeAttribute(std::string const & name,std::string const & attribute)15620     XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
15621         if( !name.empty() && !attribute.empty() )
15622             m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
15623         return *this;
15624     }
15625 
writeAttribute(std::string const & name,bool attribute)15626     XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
15627         m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
15628         return *this;
15629     }
15630 
writeText(std::string const & text,XmlFormatting fmt)15631     XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
15632         if( !text.empty() ){
15633             bool tagWasOpen = m_tagIsOpen;
15634             ensureTagClosed();
15635             if (tagWasOpen && shouldIndent(fmt)) {
15636                 m_os << m_indent;
15637             }
15638             m_os << XmlEncode( text );
15639             applyFormatting(fmt);
15640         }
15641         return *this;
15642     }
15643 
writeComment(std::string const & text,XmlFormatting fmt)15644     XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
15645         ensureTagClosed();
15646         if (shouldIndent(fmt)) {
15647             m_os << m_indent;
15648         }
15649         m_os << "<!--" << text << "-->";
15650         applyFormatting(fmt);
15651         return *this;
15652     }
15653 
writeStylesheetRef(std::string const & url)15654     void XmlWriter::writeStylesheetRef( std::string const& url ) {
15655         m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15656     }
15657 
writeBlankLine()15658     XmlWriter& XmlWriter::writeBlankLine() {
15659         ensureTagClosed();
15660         m_os << '\n';
15661         return *this;
15662     }
15663 
ensureTagClosed()15664     void XmlWriter::ensureTagClosed() {
15665         if( m_tagIsOpen ) {
15666             m_os << '>' << std::flush;
15667             newlineIfNecessary();
15668             m_tagIsOpen = false;
15669         }
15670     }
15671 
applyFormatting(XmlFormatting fmt)15672     void XmlWriter::applyFormatting(XmlFormatting fmt) {
15673         m_needsNewline = shouldNewline(fmt);
15674     }
15675 
writeDeclaration()15676     void XmlWriter::writeDeclaration() {
15677         m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15678     }
15679 
newlineIfNecessary()15680     void XmlWriter::newlineIfNecessary() {
15681         if( m_needsNewline ) {
15682             m_os << std::endl;
15683             m_needsNewline = false;
15684         }
15685     }
15686 }
15687 // end catch_xmlwriter.cpp
15688 // start catch_reporter_bases.cpp
15689 
15690 #include <cstring>
15691 #include <cfloat>
15692 #include <cstdio>
15693 #include <cassert>
15694 #include <memory>
15695 
15696 namespace Catch {
prepareExpandedExpression(AssertionResult & result)15697     void prepareExpandedExpression(AssertionResult& result) {
15698         result.getExpandedExpression();
15699     }
15700 
15701     // Because formatting using c++ streams is stateful, drop down to C is required
15702     // Alternatively we could use stringstream, but its performance is... not good.
getFormattedDuration(double duration)15703     std::string getFormattedDuration( double duration ) {
15704         // Max exponent + 1 is required to represent the whole part
15705         // + 1 for decimal point
15706         // + 3 for the 3 decimal places
15707         // + 1 for null terminator
15708         const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15709         char buffer[maxDoubleSize];
15710 
15711         // Save previous errno, to prevent sprintf from overwriting it
15712         ErrnoGuard guard;
15713 #ifdef _MSC_VER
15714         sprintf_s(buffer, "%.3f", duration);
15715 #else
15716         std::sprintf(buffer, "%.3f", duration);
15717 #endif
15718         return std::string(buffer);
15719     }
15720 
shouldShowDuration(IConfig const & config,double duration)15721     bool shouldShowDuration( IConfig const& config, double duration ) {
15722         if ( config.showDurations() == ShowDurations::Always ) {
15723             return true;
15724         }
15725         if ( config.showDurations() == ShowDurations::Never ) {
15726             return false;
15727         }
15728         const double min = config.minDuration();
15729         return min >= 0 && duration >= min;
15730     }
15731 
serializeFilters(std::vector<std::string> const & container)15732     std::string serializeFilters( std::vector<std::string> const& container ) {
15733         ReusableStringStream oss;
15734         bool first = true;
15735         for (auto&& filter : container)
15736         {
15737             if (!first)
15738                 oss << ' ';
15739             else
15740                 first = false;
15741 
15742             oss << filter;
15743         }
15744         return oss.str();
15745     }
15746 
TestEventListenerBase(ReporterConfig const & _config)15747     TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15748         :StreamingReporterBase(_config) {}
15749 
getSupportedVerbosities()15750     std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15751         return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15752     }
15753 
assertionStarting(AssertionInfo const &)15754     void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15755 
assertionEnded(AssertionStats const &)15756     bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15757         return false;
15758     }
15759 
15760 } // end namespace Catch
15761 // end catch_reporter_bases.cpp
15762 // start catch_reporter_compact.cpp
15763 
15764 namespace {
15765 
15766 #ifdef CATCH_PLATFORM_MAC
failedString()15767     const char* failedString() { return "FAILED"; }
passedString()15768     const char* passedString() { return "PASSED"; }
15769 #else
15770     const char* failedString() { return "failed"; }
15771     const char* passedString() { return "passed"; }
15772 #endif
15773 
15774     // Colour::LightGrey
dimColour()15775     Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15776 
bothOrAll(std::size_t count)15777     std::string bothOrAll( std::size_t count ) {
15778         return count == 1 ? std::string() :
15779                count == 2 ? "both " : "all " ;
15780     }
15781 
15782 } // anon namespace
15783 
15784 namespace Catch {
15785 namespace {
15786 // Colour, message variants:
15787 // - white: No tests ran.
15788 // -   red: Failed [both/all] N test cases, failed [both/all] M assertions.
15789 // - white: Passed [both/all] N test cases (no assertions).
15790 // -   red: Failed N tests cases, failed M assertions.
15791 // - green: Passed [both/all] N tests cases with M assertions.
printTotals(std::ostream & out,const Totals & totals)15792 void printTotals(std::ostream& out, const Totals& totals) {
15793     if (totals.testCases.total() == 0) {
15794         out << "No tests ran.";
15795     } else if (totals.testCases.failed == totals.testCases.total()) {
15796         Colour colour(Colour::ResultError);
15797         const std::string qualify_assertions_failed =
15798             totals.assertions.failed == totals.assertions.total() ?
15799             bothOrAll(totals.assertions.failed) : std::string();
15800         out <<
15801             "Failed " << bothOrAll(totals.testCases.failed)
15802             << pluralise(totals.testCases.failed, "test case") << ", "
15803             "failed " << qualify_assertions_failed <<
15804             pluralise(totals.assertions.failed, "assertion") << '.';
15805     } else if (totals.assertions.total() == 0) {
15806         out <<
15807             "Passed " << bothOrAll(totals.testCases.total())
15808             << pluralise(totals.testCases.total(), "test case")
15809             << " (no assertions).";
15810     } else if (totals.assertions.failed) {
15811         Colour colour(Colour::ResultError);
15812         out <<
15813             "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15814             "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15815     } else {
15816         Colour colour(Colour::ResultSuccess);
15817         out <<
15818             "Passed " << bothOrAll(totals.testCases.passed)
15819             << pluralise(totals.testCases.passed, "test case") <<
15820             " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15821     }
15822 }
15823 
15824 // Implementation of CompactReporter formatting
15825 class AssertionPrinter {
15826 public:
15827     AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15828     AssertionPrinter(AssertionPrinter const&) = delete;
AssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)15829     AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15830         : stream(_stream)
15831         , result(_stats.assertionResult)
15832         , messages(_stats.infoMessages)
15833         , itMessage(_stats.infoMessages.begin())
15834         , printInfoMessages(_printInfoMessages) {}
15835 
print()15836     void print() {
15837         printSourceInfo();
15838 
15839         itMessage = messages.begin();
15840 
15841         switch (result.getResultType()) {
15842         case ResultWas::Ok:
15843             printResultType(Colour::ResultSuccess, passedString());
15844             printOriginalExpression();
15845             printReconstructedExpression();
15846             if (!result.hasExpression())
15847                 printRemainingMessages(Colour::None);
15848             else
15849                 printRemainingMessages();
15850             break;
15851         case ResultWas::ExpressionFailed:
15852             if (result.isOk())
15853                 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15854             else
15855                 printResultType(Colour::Error, failedString());
15856             printOriginalExpression();
15857             printReconstructedExpression();
15858             printRemainingMessages();
15859             break;
15860         case ResultWas::ThrewException:
15861             printResultType(Colour::Error, failedString());
15862             printIssue("unexpected exception with message:");
15863             printMessage();
15864             printExpressionWas();
15865             printRemainingMessages();
15866             break;
15867         case ResultWas::FatalErrorCondition:
15868             printResultType(Colour::Error, failedString());
15869             printIssue("fatal error condition with message:");
15870             printMessage();
15871             printExpressionWas();
15872             printRemainingMessages();
15873             break;
15874         case ResultWas::DidntThrowException:
15875             printResultType(Colour::Error, failedString());
15876             printIssue("expected exception, got none");
15877             printExpressionWas();
15878             printRemainingMessages();
15879             break;
15880         case ResultWas::Info:
15881             printResultType(Colour::None, "info");
15882             printMessage();
15883             printRemainingMessages();
15884             break;
15885         case ResultWas::Warning:
15886             printResultType(Colour::None, "warning");
15887             printMessage();
15888             printRemainingMessages();
15889             break;
15890         case ResultWas::ExplicitFailure:
15891             printResultType(Colour::Error, failedString());
15892             printIssue("explicitly");
15893             printRemainingMessages(Colour::None);
15894             break;
15895             // These cases are here to prevent compiler warnings
15896         case ResultWas::Unknown:
15897         case ResultWas::FailureBit:
15898         case ResultWas::Exception:
15899             printResultType(Colour::Error, "** internal error **");
15900             break;
15901         }
15902     }
15903 
15904 private:
printSourceInfo() const15905     void printSourceInfo() const {
15906         Colour colourGuard(Colour::FileName);
15907         stream << result.getSourceInfo() << ':';
15908     }
15909 
printResultType(Colour::Code colour,std::string const & passOrFail) const15910     void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15911         if (!passOrFail.empty()) {
15912             {
15913                 Colour colourGuard(colour);
15914                 stream << ' ' << passOrFail;
15915             }
15916             stream << ':';
15917         }
15918     }
15919 
printIssue(std::string const & issue) const15920     void printIssue(std::string const& issue) const {
15921         stream << ' ' << issue;
15922     }
15923 
printExpressionWas()15924     void printExpressionWas() {
15925         if (result.hasExpression()) {
15926             stream << ';';
15927             {
15928                 Colour colour(dimColour());
15929                 stream << " expression was:";
15930             }
15931             printOriginalExpression();
15932         }
15933     }
15934 
printOriginalExpression() const15935     void printOriginalExpression() const {
15936         if (result.hasExpression()) {
15937             stream << ' ' << result.getExpression();
15938         }
15939     }
15940 
printReconstructedExpression() const15941     void printReconstructedExpression() const {
15942         if (result.hasExpandedExpression()) {
15943             {
15944                 Colour colour(dimColour());
15945                 stream << " for: ";
15946             }
15947             stream << result.getExpandedExpression();
15948         }
15949     }
15950 
printMessage()15951     void printMessage() {
15952         if (itMessage != messages.end()) {
15953             stream << " '" << itMessage->message << '\'';
15954             ++itMessage;
15955         }
15956     }
15957 
printRemainingMessages(Colour::Code colour=dimColour ())15958     void printRemainingMessages(Colour::Code colour = dimColour()) {
15959         if (itMessage == messages.end())
15960             return;
15961 
15962         const auto itEnd = messages.cend();
15963         const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
15964 
15965         {
15966             Colour colourGuard(colour);
15967             stream << " with " << pluralise(N, "message") << ':';
15968         }
15969 
15970         while (itMessage != itEnd) {
15971             // If this assertion is a warning ignore any INFO messages
15972             if (printInfoMessages || itMessage->type != ResultWas::Info) {
15973                 printMessage();
15974                 if (itMessage != itEnd) {
15975                     Colour colourGuard(dimColour());
15976                     stream << " and";
15977                 }
15978                 continue;
15979             }
15980             ++itMessage;
15981         }
15982     }
15983 
15984 private:
15985     std::ostream& stream;
15986     AssertionResult const& result;
15987     std::vector<MessageInfo> messages;
15988     std::vector<MessageInfo>::const_iterator itMessage;
15989     bool printInfoMessages;
15990 };
15991 
15992 } // anon namespace
15993 
getDescription()15994         std::string CompactReporter::getDescription() {
15995             return "Reports test results on a single line, suitable for IDEs";
15996         }
15997 
noMatchingTestCases(std::string const & spec)15998         void CompactReporter::noMatchingTestCases( std::string const& spec ) {
15999             stream << "No test cases matched '" << spec << '\'' << std::endl;
16000         }
16001 
assertionStarting(AssertionInfo const &)16002         void CompactReporter::assertionStarting( AssertionInfo const& ) {}
16003 
assertionEnded(AssertionStats const & _assertionStats)16004         bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
16005             AssertionResult const& result = _assertionStats.assertionResult;
16006 
16007             bool printInfoMessages = true;
16008 
16009             // Drop out if result was successful and we're not printing those
16010             if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16011                 if( result.getResultType() != ResultWas::Warning )
16012                     return false;
16013                 printInfoMessages = false;
16014             }
16015 
16016             AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16017             printer.print();
16018 
16019             stream << std::endl;
16020             return true;
16021         }
16022 
sectionEnded(SectionStats const & _sectionStats)16023         void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16024             double dur = _sectionStats.durationInSeconds;
16025             if ( shouldShowDuration( *m_config, dur ) ) {
16026                 stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16027             }
16028         }
16029 
testRunEnded(TestRunStats const & _testRunStats)16030         void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
16031             printTotals( stream, _testRunStats.totals );
16032             stream << '\n' << std::endl;
16033             StreamingReporterBase::testRunEnded( _testRunStats );
16034         }
16035 
~CompactReporter()16036         CompactReporter::~CompactReporter() {}
16037 
16038     CATCH_REGISTER_REPORTER( "compact", CompactReporter )
16039 
16040 } // end namespace Catch
16041 // end catch_reporter_compact.cpp
16042 // start catch_reporter_console.cpp
16043 
16044 #include <cfloat>
16045 #include <cstdio>
16046 
16047 #if defined(_MSC_VER)
16048 #pragma warning(push)
16049 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16050  // Note that 4062 (not all labels are handled and default is missing) is enabled
16051 #endif
16052 
16053 #if defined(__clang__)
16054 #  pragma clang diagnostic push
16055 // For simplicity, benchmarking-only helpers are always enabled
16056 #  pragma clang diagnostic ignored "-Wunused-function"
16057 #endif
16058 
16059 namespace Catch {
16060 
16061 namespace {
16062 
16063 // Formatter impl for ConsoleReporter
16064 class ConsoleAssertionPrinter {
16065 public:
16066     ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
16067     ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
ConsoleAssertionPrinter(std::ostream & _stream,AssertionStats const & _stats,bool _printInfoMessages)16068     ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
16069         : stream(_stream),
16070         stats(_stats),
16071         result(_stats.assertionResult),
16072         colour(Colour::None),
16073         message(result.getMessage()),
16074         messages(_stats.infoMessages),
16075         printInfoMessages(_printInfoMessages) {
16076         switch (result.getResultType()) {
16077         case ResultWas::Ok:
16078             colour = Colour::Success;
16079             passOrFail = "PASSED";
16080             //if( result.hasMessage() )
16081             if (_stats.infoMessages.size() == 1)
16082                 messageLabel = "with message";
16083             if (_stats.infoMessages.size() > 1)
16084                 messageLabel = "with messages";
16085             break;
16086         case ResultWas::ExpressionFailed:
16087             if (result.isOk()) {
16088                 colour = Colour::Success;
16089                 passOrFail = "FAILED - but was ok";
16090             } else {
16091                 colour = Colour::Error;
16092                 passOrFail = "FAILED";
16093             }
16094             if (_stats.infoMessages.size() == 1)
16095                 messageLabel = "with message";
16096             if (_stats.infoMessages.size() > 1)
16097                 messageLabel = "with messages";
16098             break;
16099         case ResultWas::ThrewException:
16100             colour = Colour::Error;
16101             passOrFail = "FAILED";
16102             messageLabel = "due to unexpected exception with ";
16103             if (_stats.infoMessages.size() == 1)
16104                 messageLabel += "message";
16105             if (_stats.infoMessages.size() > 1)
16106                 messageLabel += "messages";
16107             break;
16108         case ResultWas::FatalErrorCondition:
16109             colour = Colour::Error;
16110             passOrFail = "FAILED";
16111             messageLabel = "due to a fatal error condition";
16112             break;
16113         case ResultWas::DidntThrowException:
16114             colour = Colour::Error;
16115             passOrFail = "FAILED";
16116             messageLabel = "because no exception was thrown where one was expected";
16117             break;
16118         case ResultWas::Info:
16119             messageLabel = "info";
16120             break;
16121         case ResultWas::Warning:
16122             messageLabel = "warning";
16123             break;
16124         case ResultWas::ExplicitFailure:
16125             passOrFail = "FAILED";
16126             colour = Colour::Error;
16127             if (_stats.infoMessages.size() == 1)
16128                 messageLabel = "explicitly with message";
16129             if (_stats.infoMessages.size() > 1)
16130                 messageLabel = "explicitly with messages";
16131             break;
16132             // These cases are here to prevent compiler warnings
16133         case ResultWas::Unknown:
16134         case ResultWas::FailureBit:
16135         case ResultWas::Exception:
16136             passOrFail = "** internal error **";
16137             colour = Colour::Error;
16138             break;
16139         }
16140     }
16141 
print() const16142     void print() const {
16143         printSourceInfo();
16144         if (stats.totals.assertions.total() > 0) {
16145             printResultType();
16146             printOriginalExpression();
16147             printReconstructedExpression();
16148         } else {
16149             stream << '\n';
16150         }
16151         printMessage();
16152     }
16153 
16154 private:
printResultType() const16155     void printResultType() const {
16156         if (!passOrFail.empty()) {
16157             Colour colourGuard(colour);
16158             stream << passOrFail << ":\n";
16159         }
16160     }
printOriginalExpression() const16161     void printOriginalExpression() const {
16162         if (result.hasExpression()) {
16163             Colour colourGuard(Colour::OriginalExpression);
16164             stream << "  ";
16165             stream << result.getExpressionInMacro();
16166             stream << '\n';
16167         }
16168     }
printReconstructedExpression() const16169     void printReconstructedExpression() const {
16170         if (result.hasExpandedExpression()) {
16171             stream << "with expansion:\n";
16172             Colour colourGuard(Colour::ReconstructedExpression);
16173             stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16174         }
16175     }
printMessage() const16176     void printMessage() const {
16177         if (!messageLabel.empty())
16178             stream << messageLabel << ':' << '\n';
16179         for (auto const& msg : messages) {
16180             // If this assertion is a warning ignore any INFO messages
16181             if (printInfoMessages || msg.type != ResultWas::Info)
16182                 stream << Column(msg.message).indent(2) << '\n';
16183         }
16184     }
printSourceInfo() const16185     void printSourceInfo() const {
16186         Colour colourGuard(Colour::FileName);
16187         stream << result.getSourceInfo() << ": ";
16188     }
16189 
16190     std::ostream& stream;
16191     AssertionStats const& stats;
16192     AssertionResult const& result;
16193     Colour::Code colour;
16194     std::string passOrFail;
16195     std::string messageLabel;
16196     std::string message;
16197     std::vector<MessageInfo> messages;
16198     bool printInfoMessages;
16199 };
16200 
makeRatio(std::size_t number,std::size_t total)16201 std::size_t makeRatio(std::size_t number, std::size_t total) {
16202     std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16203     return (ratio == 0 && number > 0) ? 1 : ratio;
16204 }
16205 
findMax(std::size_t & i,std::size_t & j,std::size_t & k)16206 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16207     if (i > j && i > k)
16208         return i;
16209     else if (j > k)
16210         return j;
16211     else
16212         return k;
16213 }
16214 
16215 struct ColumnInfo {
16216     enum Justification { Left, Right };
16217     std::string name;
16218     int width;
16219     Justification justification;
16220 };
16221 struct ColumnBreak {};
16222 struct RowBreak {};
16223 
16224 class Duration {
16225     enum class Unit {
16226         Auto,
16227         Nanoseconds,
16228         Microseconds,
16229         Milliseconds,
16230         Seconds,
16231         Minutes
16232     };
16233     static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16234     static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16235     static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16236     static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16237 
16238     double m_inNanoseconds;
16239     Unit m_units;
16240 
16241 public:
Duration(double inNanoseconds,Unit units=Unit::Auto)16242     explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16243         : m_inNanoseconds(inNanoseconds),
16244         m_units(units) {
16245         if (m_units == Unit::Auto) {
16246             if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16247                 m_units = Unit::Nanoseconds;
16248             else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16249                 m_units = Unit::Microseconds;
16250             else if (m_inNanoseconds < s_nanosecondsInASecond)
16251                 m_units = Unit::Milliseconds;
16252             else if (m_inNanoseconds < s_nanosecondsInAMinute)
16253                 m_units = Unit::Seconds;
16254             else
16255                 m_units = Unit::Minutes;
16256         }
16257 
16258     }
16259 
value() const16260     auto value() const -> double {
16261         switch (m_units) {
16262         case Unit::Microseconds:
16263             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16264         case Unit::Milliseconds:
16265             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16266         case Unit::Seconds:
16267             return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16268         case Unit::Minutes:
16269             return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16270         default:
16271             return m_inNanoseconds;
16272         }
16273     }
unitsAsString() const16274     auto unitsAsString() const -> std::string {
16275         switch (m_units) {
16276         case Unit::Nanoseconds:
16277             return "ns";
16278         case Unit::Microseconds:
16279             return "us";
16280         case Unit::Milliseconds:
16281             return "ms";
16282         case Unit::Seconds:
16283             return "s";
16284         case Unit::Minutes:
16285             return "m";
16286         default:
16287             return "** internal error **";
16288         }
16289 
16290     }
operator <<(std::ostream & os,Duration const & duration)16291     friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
16292         return os << duration.value() << ' ' << duration.unitsAsString();
16293     }
16294 };
16295 } // end anon namespace
16296 
16297 class TablePrinter {
16298     std::ostream& m_os;
16299     std::vector<ColumnInfo> m_columnInfos;
16300     std::ostringstream m_oss;
16301     int m_currentColumn = -1;
16302     bool m_isOpen = false;
16303 
16304 public:
TablePrinter(std::ostream & os,std::vector<ColumnInfo> columnInfos)16305     TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16306     :   m_os( os ),
16307         m_columnInfos( std::move( columnInfos ) ) {}
16308 
columnInfos() const16309     auto columnInfos() const -> std::vector<ColumnInfo> const& {
16310         return m_columnInfos;
16311     }
16312 
open()16313     void open() {
16314         if (!m_isOpen) {
16315             m_isOpen = true;
16316             *this << RowBreak();
16317 
16318 			Columns headerCols;
16319 			Spacer spacer(2);
16320 			for (auto const& info : m_columnInfos) {
16321 				headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16322 				headerCols += spacer;
16323 			}
16324 			m_os << headerCols << '\n';
16325 
16326             m_os << Catch::getLineOfChars<'-'>() << '\n';
16327         }
16328     }
close()16329     void close() {
16330         if (m_isOpen) {
16331             *this << RowBreak();
16332             m_os << std::endl;
16333             m_isOpen = false;
16334         }
16335     }
16336 
16337     template<typename T>
operator <<(TablePrinter & tp,T const & value)16338     friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
16339         tp.m_oss << value;
16340         return tp;
16341     }
16342 
operator <<(TablePrinter & tp,ColumnBreak)16343     friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16344         auto colStr = tp.m_oss.str();
16345         const auto strSize = colStr.size();
16346         tp.m_oss.str("");
16347         tp.open();
16348         if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16349             tp.m_currentColumn = -1;
16350             tp.m_os << '\n';
16351         }
16352         tp.m_currentColumn++;
16353 
16354         auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16355         auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16356             ? std::string(colInfo.width - (strSize + 1), ' ')
16357             : std::string();
16358         if (colInfo.justification == ColumnInfo::Left)
16359             tp.m_os << colStr << padding << ' ';
16360         else
16361             tp.m_os << padding << colStr << ' ';
16362         return tp;
16363     }
16364 
operator <<(TablePrinter & tp,RowBreak)16365     friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16366         if (tp.m_currentColumn > 0) {
16367             tp.m_os << '\n';
16368             tp.m_currentColumn = -1;
16369         }
16370         return tp;
16371     }
16372 };
16373 
ConsoleReporter(ReporterConfig const & config)16374 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16375     : StreamingReporterBase(config),
16376     m_tablePrinter(new TablePrinter(config.stream(),
16377         [&config]() -> std::vector<ColumnInfo> {
16378         if (config.fullConfig()->benchmarkNoAnalysis())
16379         {
16380             return{
16381                 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16382                 { "     samples", 14, ColumnInfo::Right },
16383                 { "  iterations", 14, ColumnInfo::Right },
16384                 { "        mean", 14, ColumnInfo::Right }
16385             };
16386         }
16387         else
16388         {
16389             return{
16390                 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16391                 { "samples      mean       std dev", 14, ColumnInfo::Right },
16392                 { "iterations   low mean   low std dev", 14, ColumnInfo::Right },
16393                 { "estimated    high mean  high std dev", 14, ColumnInfo::Right }
16394             };
16395         }
16396     }())) {}
16397 ConsoleReporter::~ConsoleReporter() = default;
16398 
getDescription()16399 std::string ConsoleReporter::getDescription() {
16400     return "Reports test results as plain lines of text";
16401 }
16402 
noMatchingTestCases(std::string const & spec)16403 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16404     stream << "No test cases matched '" << spec << '\'' << std::endl;
16405 }
16406 
reportInvalidArguments(std::string const & arg)16407 void ConsoleReporter::reportInvalidArguments(std::string const&arg){
16408     stream << "Invalid Filter: " << arg << std::endl;
16409 }
16410 
assertionStarting(AssertionInfo const &)16411 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16412 
assertionEnded(AssertionStats const & _assertionStats)16413 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16414     AssertionResult const& result = _assertionStats.assertionResult;
16415 
16416     bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16417 
16418     // Drop out if result was successful but we're not printing them.
16419     if (!includeResults && result.getResultType() != ResultWas::Warning)
16420         return false;
16421 
16422     lazyPrint();
16423 
16424     ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16425     printer.print();
16426     stream << std::endl;
16427     return true;
16428 }
16429 
sectionStarting(SectionInfo const & _sectionInfo)16430 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16431     m_tablePrinter->close();
16432     m_headerPrinted = false;
16433     StreamingReporterBase::sectionStarting(_sectionInfo);
16434 }
sectionEnded(SectionStats const & _sectionStats)16435 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16436     m_tablePrinter->close();
16437     if (_sectionStats.missingAssertions) {
16438         lazyPrint();
16439         Colour colour(Colour::ResultError);
16440         if (m_sectionStack.size() > 1)
16441             stream << "\nNo assertions in section";
16442         else
16443             stream << "\nNo assertions in test case";
16444         stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16445     }
16446     double dur = _sectionStats.durationInSeconds;
16447     if (shouldShowDuration(*m_config, dur)) {
16448         stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16449     }
16450     if (m_headerPrinted) {
16451         m_headerPrinted = false;
16452     }
16453     StreamingReporterBase::sectionEnded(_sectionStats);
16454 }
16455 
16456 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)16457 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16458 	lazyPrintWithoutClosingBenchmarkTable();
16459 
16460 	auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16461 
16462 	bool firstLine = true;
16463 	for (auto line : nameCol) {
16464 		if (!firstLine)
16465 			(*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16466 		else
16467 			firstLine = false;
16468 
16469 		(*m_tablePrinter) << line << ColumnBreak();
16470 	}
16471 }
16472 
benchmarkStarting(BenchmarkInfo const & info)16473 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16474     (*m_tablePrinter) << info.samples << ColumnBreak()
16475         << info.iterations << ColumnBreak();
16476     if (!m_config->benchmarkNoAnalysis())
16477         (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16478 }
benchmarkEnded(BenchmarkStats<> const & stats)16479 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16480     if (m_config->benchmarkNoAnalysis())
16481     {
16482         (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16483     }
16484     else
16485     {
16486         (*m_tablePrinter) << ColumnBreak()
16487             << Duration(stats.mean.point.count()) << ColumnBreak()
16488             << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16489             << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16490             << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16491             << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16492             << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16493     }
16494 }
16495 
benchmarkFailed(std::string const & error)16496 void ConsoleReporter::benchmarkFailed(std::string const& error) {
16497 	Colour colour(Colour::Red);
16498     (*m_tablePrinter)
16499         << "Benchmark failed (" << error << ')'
16500         << ColumnBreak() << RowBreak();
16501 }
16502 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16503 
testCaseEnded(TestCaseStats const & _testCaseStats)16504 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16505     m_tablePrinter->close();
16506     StreamingReporterBase::testCaseEnded(_testCaseStats);
16507     m_headerPrinted = false;
16508 }
testGroupEnded(TestGroupStats const & _testGroupStats)16509 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16510     if (currentGroupInfo.used) {
16511         printSummaryDivider();
16512         stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16513         printTotals(_testGroupStats.totals);
16514         stream << '\n' << std::endl;
16515     }
16516     StreamingReporterBase::testGroupEnded(_testGroupStats);
16517 }
testRunEnded(TestRunStats const & _testRunStats)16518 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16519     printTotalsDivider(_testRunStats.totals);
16520     printTotals(_testRunStats.totals);
16521     stream << std::endl;
16522     StreamingReporterBase::testRunEnded(_testRunStats);
16523 }
testRunStarting(TestRunInfo const & _testInfo)16524 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16525     StreamingReporterBase::testRunStarting(_testInfo);
16526     printTestFilters();
16527 }
16528 
lazyPrint()16529 void ConsoleReporter::lazyPrint() {
16530 
16531     m_tablePrinter->close();
16532     lazyPrintWithoutClosingBenchmarkTable();
16533 }
16534 
lazyPrintWithoutClosingBenchmarkTable()16535 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16536 
16537     if (!currentTestRunInfo.used)
16538         lazyPrintRunInfo();
16539     if (!currentGroupInfo.used)
16540         lazyPrintGroupInfo();
16541 
16542     if (!m_headerPrinted) {
16543         printTestCaseAndSectionHeader();
16544         m_headerPrinted = true;
16545     }
16546 }
lazyPrintRunInfo()16547 void ConsoleReporter::lazyPrintRunInfo() {
16548     stream << '\n' << getLineOfChars<'~'>() << '\n';
16549     Colour colour(Colour::SecondaryText);
16550     stream << currentTestRunInfo->name
16551         << " is a Catch v" << libraryVersion() << " host application.\n"
16552         << "Run with -? for options\n\n";
16553 
16554     if (m_config->rngSeed() != 0)
16555         stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16556 
16557     currentTestRunInfo.used = true;
16558 }
lazyPrintGroupInfo()16559 void ConsoleReporter::lazyPrintGroupInfo() {
16560     if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16561         printClosedHeader("Group: " + currentGroupInfo->name);
16562         currentGroupInfo.used = true;
16563     }
16564 }
printTestCaseAndSectionHeader()16565 void ConsoleReporter::printTestCaseAndSectionHeader() {
16566     assert(!m_sectionStack.empty());
16567     printOpenHeader(currentTestCaseInfo->name);
16568 
16569     if (m_sectionStack.size() > 1) {
16570         Colour colourGuard(Colour::Headers);
16571 
16572         auto
16573             it = m_sectionStack.begin() + 1, // Skip first section (test case)
16574             itEnd = m_sectionStack.end();
16575         for (; it != itEnd; ++it)
16576             printHeaderString(it->name, 2);
16577     }
16578 
16579     SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16580 
16581     stream << getLineOfChars<'-'>() << '\n';
16582     Colour colourGuard(Colour::FileName);
16583     stream << lineInfo << '\n';
16584     stream << getLineOfChars<'.'>() << '\n' << std::endl;
16585 }
16586 
printClosedHeader(std::string const & _name)16587 void ConsoleReporter::printClosedHeader(std::string const& _name) {
16588     printOpenHeader(_name);
16589     stream << getLineOfChars<'.'>() << '\n';
16590 }
printOpenHeader(std::string const & _name)16591 void ConsoleReporter::printOpenHeader(std::string const& _name) {
16592     stream << getLineOfChars<'-'>() << '\n';
16593     {
16594         Colour colourGuard(Colour::Headers);
16595         printHeaderString(_name);
16596     }
16597 }
16598 
16599 // if string has a : in first line will set indent to follow it on
16600 // subsequent lines
printHeaderString(std::string const & _string,std::size_t indent)16601 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16602     std::size_t i = _string.find(": ");
16603     if (i != std::string::npos)
16604         i += 2;
16605     else
16606         i = 0;
16607     stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16608 }
16609 
16610 struct SummaryColumn {
16611 
SummaryColumnCatch::SummaryColumn16612     SummaryColumn( std::string _label, Colour::Code _colour )
16613     :   label( std::move( _label ) ),
16614         colour( _colour ) {}
addRowCatch::SummaryColumn16615     SummaryColumn addRow( std::size_t count ) {
16616         ReusableStringStream rss;
16617         rss << count;
16618         std::string row = rss.str();
16619         for (auto& oldRow : rows) {
16620             while (oldRow.size() < row.size())
16621                 oldRow = ' ' + oldRow;
16622             while (oldRow.size() > row.size())
16623                 row = ' ' + row;
16624         }
16625         rows.push_back(row);
16626         return *this;
16627     }
16628 
16629     std::string label;
16630     Colour::Code colour;
16631     std::vector<std::string> rows;
16632 
16633 };
16634 
printTotals(Totals const & totals)16635 void ConsoleReporter::printTotals( Totals const& totals ) {
16636     if (totals.testCases.total() == 0) {
16637         stream << Colour(Colour::Warning) << "No tests ran\n";
16638     } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16639         stream << Colour(Colour::ResultSuccess) << "All tests passed";
16640         stream << " ("
16641             << pluralise(totals.assertions.passed, "assertion") << " in "
16642             << pluralise(totals.testCases.passed, "test case") << ')'
16643             << '\n';
16644     } else {
16645 
16646         std::vector<SummaryColumn> columns;
16647         columns.push_back(SummaryColumn("", Colour::None)
16648                           .addRow(totals.testCases.total())
16649                           .addRow(totals.assertions.total()));
16650         columns.push_back(SummaryColumn("passed", Colour::Success)
16651                           .addRow(totals.testCases.passed)
16652                           .addRow(totals.assertions.passed));
16653         columns.push_back(SummaryColumn("failed", Colour::ResultError)
16654                           .addRow(totals.testCases.failed)
16655                           .addRow(totals.assertions.failed));
16656         columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16657                           .addRow(totals.testCases.failedButOk)
16658                           .addRow(totals.assertions.failedButOk));
16659 
16660         printSummaryRow("test cases", columns, 0);
16661         printSummaryRow("assertions", columns, 1);
16662     }
16663 }
printSummaryRow(std::string const & label,std::vector<SummaryColumn> const & cols,std::size_t row)16664 void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
16665     for (auto col : cols) {
16666         std::string value = col.rows[row];
16667         if (col.label.empty()) {
16668             stream << label << ": ";
16669             if (value != "0")
16670                 stream << value;
16671             else
16672                 stream << Colour(Colour::Warning) << "- none -";
16673         } else if (value != "0") {
16674             stream << Colour(Colour::LightGrey) << " | ";
16675             stream << Colour(col.colour)
16676                 << value << ' ' << col.label;
16677         }
16678     }
16679     stream << '\n';
16680 }
16681 
printTotalsDivider(Totals const & totals)16682 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16683     if (totals.testCases.total() > 0) {
16684         std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16685         std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16686         std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16687         while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16688             findMax(failedRatio, failedButOkRatio, passedRatio)++;
16689         while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16690             findMax(failedRatio, failedButOkRatio, passedRatio)--;
16691 
16692         stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16693         stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16694         if (totals.testCases.allPassed())
16695             stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16696         else
16697             stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16698     } else {
16699         stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16700     }
16701     stream << '\n';
16702 }
printSummaryDivider()16703 void ConsoleReporter::printSummaryDivider() {
16704     stream << getLineOfChars<'-'>() << '\n';
16705 }
16706 
printTestFilters()16707 void ConsoleReporter::printTestFilters() {
16708     if (m_config->testSpec().hasFilters()) {
16709         Colour guard(Colour::BrightYellow);
16710         stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16711     }
16712 }
16713 
16714 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16715 
16716 } // end namespace Catch
16717 
16718 #if defined(_MSC_VER)
16719 #pragma warning(pop)
16720 #endif
16721 
16722 #if defined(__clang__)
16723 #  pragma clang diagnostic pop
16724 #endif
16725 // end catch_reporter_console.cpp
16726 // start catch_reporter_junit.cpp
16727 
16728 #include <cassert>
16729 #include <sstream>
16730 #include <ctime>
16731 #include <algorithm>
16732 
16733 namespace Catch {
16734 
16735     namespace {
getCurrentTimestamp()16736         std::string getCurrentTimestamp() {
16737             // Beware, this is not reentrant because of backward compatibility issues
16738             // Also, UTC only, again because of backward compatibility (%z is C++11)
16739             time_t rawtime;
16740             std::time(&rawtime);
16741             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16742 
16743 #ifdef _MSC_VER
16744             std::tm timeInfo = {};
16745             gmtime_s(&timeInfo, &rawtime);
16746 #else
16747             std::tm* timeInfo;
16748             timeInfo = std::gmtime(&rawtime);
16749 #endif
16750 
16751             char timeStamp[timeStampSize];
16752             const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
16753 
16754 #ifdef _MSC_VER
16755             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16756 #else
16757             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16758 #endif
16759             return std::string(timeStamp);
16760         }
16761 
fileNameTag(const std::vector<std::string> & tags)16762         std::string fileNameTag(const std::vector<std::string> &tags) {
16763             auto it = std::find_if(begin(tags),
16764                                    end(tags),
16765                                    [] (std::string const& tag) {return tag.front() == '#'; });
16766             if (it != tags.end())
16767                 return it->substr(1);
16768             return std::string();
16769         }
16770     } // anonymous namespace
16771 
JunitReporter(ReporterConfig const & _config)16772     JunitReporter::JunitReporter( ReporterConfig const& _config )
16773         :   CumulativeReporterBase( _config ),
16774             xml( _config.stream() )
16775         {
16776             m_reporterPrefs.shouldRedirectStdOut = true;
16777             m_reporterPrefs.shouldReportAllAssertions = true;
16778         }
16779 
~JunitReporter()16780     JunitReporter::~JunitReporter() {}
16781 
getDescription()16782     std::string JunitReporter::getDescription() {
16783         return "Reports test results in an XML format that looks like Ant's junitreport target";
16784     }
16785 
noMatchingTestCases(std::string const &)16786     void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16787 
testRunStarting(TestRunInfo const & runInfo)16788     void JunitReporter::testRunStarting( TestRunInfo const& runInfo )  {
16789         CumulativeReporterBase::testRunStarting( runInfo );
16790         xml.startElement( "testsuites" );
16791     }
16792 
testGroupStarting(GroupInfo const & groupInfo)16793     void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16794         suiteTimer.start();
16795         stdOutForSuite.clear();
16796         stdErrForSuite.clear();
16797         unexpectedExceptions = 0;
16798         CumulativeReporterBase::testGroupStarting( groupInfo );
16799     }
16800 
testCaseStarting(TestCaseInfo const & testCaseInfo)16801     void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16802         m_okToFail = testCaseInfo.okToFail();
16803     }
16804 
assertionEnded(AssertionStats const & assertionStats)16805     bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16806         if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16807             unexpectedExceptions++;
16808         return CumulativeReporterBase::assertionEnded( assertionStats );
16809     }
16810 
testCaseEnded(TestCaseStats const & testCaseStats)16811     void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16812         stdOutForSuite += testCaseStats.stdOut;
16813         stdErrForSuite += testCaseStats.stdErr;
16814         CumulativeReporterBase::testCaseEnded( testCaseStats );
16815     }
16816 
testGroupEnded(TestGroupStats const & testGroupStats)16817     void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16818         double suiteTime = suiteTimer.getElapsedSeconds();
16819         CumulativeReporterBase::testGroupEnded( testGroupStats );
16820         writeGroup( *m_testGroups.back(), suiteTime );
16821     }
16822 
testRunEndedCumulative()16823     void JunitReporter::testRunEndedCumulative() {
16824         xml.endElement();
16825     }
16826 
writeGroup(TestGroupNode const & groupNode,double suiteTime)16827     void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16828         XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16829 
16830         TestGroupStats const& stats = groupNode.value;
16831         xml.writeAttribute( "name", stats.groupInfo.name );
16832         xml.writeAttribute( "errors", unexpectedExceptions );
16833         xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16834         xml.writeAttribute( "tests", stats.totals.assertions.total() );
16835         xml.writeAttribute( "hostname", "tbd" ); // !TBD
16836         if( m_config->showDurations() == ShowDurations::Never )
16837             xml.writeAttribute( "time", "" );
16838         else
16839             xml.writeAttribute( "time", suiteTime );
16840         xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16841 
16842         // Write properties if there are any
16843         if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16844             auto properties = xml.scopedElement("properties");
16845             if (m_config->hasTestFilters()) {
16846                 xml.scopedElement("property")
16847                     .writeAttribute("name", "filters")
16848                     .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16849             }
16850             if (m_config->rngSeed() != 0) {
16851                 xml.scopedElement("property")
16852                     .writeAttribute("name", "random-seed")
16853                     .writeAttribute("value", m_config->rngSeed());
16854             }
16855         }
16856 
16857         // Write test cases
16858         for( auto const& child : groupNode.children )
16859             writeTestCase( *child );
16860 
16861         xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16862         xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16863     }
16864 
writeTestCase(TestCaseNode const & testCaseNode)16865     void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16866         TestCaseStats const& stats = testCaseNode.value;
16867 
16868         // All test cases have exactly one section - which represents the
16869         // test case itself. That section may have 0-n nested sections
16870         assert( testCaseNode.children.size() == 1 );
16871         SectionNode const& rootSection = *testCaseNode.children.front();
16872 
16873         std::string className = stats.testInfo.className;
16874 
16875         if( className.empty() ) {
16876             className = fileNameTag(stats.testInfo.tags);
16877             if ( className.empty() )
16878                 className = "global";
16879         }
16880 
16881         if ( !m_config->name().empty() )
16882             className = m_config->name() + "." + className;
16883 
16884         writeSection( className, "", rootSection );
16885     }
16886 
writeSection(std::string const & className,std::string const & rootName,SectionNode const & sectionNode)16887     void JunitReporter::writeSection(  std::string const& className,
16888                         std::string const& rootName,
16889                         SectionNode const& sectionNode ) {
16890         std::string name = trim( sectionNode.stats.sectionInfo.name );
16891         if( !rootName.empty() )
16892             name = rootName + '/' + name;
16893 
16894         if( !sectionNode.assertions.empty() ||
16895             !sectionNode.stdOut.empty() ||
16896             !sectionNode.stdErr.empty() ) {
16897             XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16898             if( className.empty() ) {
16899                 xml.writeAttribute( "classname", name );
16900                 xml.writeAttribute( "name", "root" );
16901             }
16902             else {
16903                 xml.writeAttribute( "classname", className );
16904                 xml.writeAttribute( "name", name );
16905             }
16906             xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
16907             // This is not ideal, but it should be enough to mimic gtest's
16908             // junit output.
16909             // Ideally the JUnit reporter would also handle `skipTest`
16910             // events and write those out appropriately.
16911             xml.writeAttribute( "status", "run" );
16912 
16913             writeAssertions( sectionNode );
16914 
16915             if( !sectionNode.stdOut.empty() )
16916                 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
16917             if( !sectionNode.stdErr.empty() )
16918                 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
16919         }
16920         for( auto const& childNode : sectionNode.childSections )
16921             if( className.empty() )
16922                 writeSection( name, "", *childNode );
16923             else
16924                 writeSection( className, name, *childNode );
16925     }
16926 
writeAssertions(SectionNode const & sectionNode)16927     void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
16928         for( auto const& assertion : sectionNode.assertions )
16929             writeAssertion( assertion );
16930     }
16931 
writeAssertion(AssertionStats const & stats)16932     void JunitReporter::writeAssertion( AssertionStats const& stats ) {
16933         AssertionResult const& result = stats.assertionResult;
16934         if( !result.isOk() ) {
16935             std::string elementName;
16936             switch( result.getResultType() ) {
16937                 case ResultWas::ThrewException:
16938                 case ResultWas::FatalErrorCondition:
16939                     elementName = "error";
16940                     break;
16941                 case ResultWas::ExplicitFailure:
16942                 case ResultWas::ExpressionFailed:
16943                 case ResultWas::DidntThrowException:
16944                     elementName = "failure";
16945                     break;
16946 
16947                 // We should never see these here:
16948                 case ResultWas::Info:
16949                 case ResultWas::Warning:
16950                 case ResultWas::Ok:
16951                 case ResultWas::Unknown:
16952                 case ResultWas::FailureBit:
16953                 case ResultWas::Exception:
16954                     elementName = "internalError";
16955                     break;
16956             }
16957 
16958             XmlWriter::ScopedElement e = xml.scopedElement( elementName );
16959 
16960             xml.writeAttribute( "message", result.getExpression() );
16961             xml.writeAttribute( "type", result.getTestMacroName() );
16962 
16963             ReusableStringStream rss;
16964             if (stats.totals.assertions.total() > 0) {
16965                 rss << "FAILED" << ":\n";
16966                 if (result.hasExpression()) {
16967                     rss << "  ";
16968                     rss << result.getExpressionInMacro();
16969                     rss << '\n';
16970                 }
16971                 if (result.hasExpandedExpression()) {
16972                     rss << "with expansion:\n";
16973                     rss << Column(result.getExpandedExpression()).indent(2) << '\n';
16974                 }
16975             } else {
16976                 rss << '\n';
16977             }
16978 
16979             if( !result.getMessage().empty() )
16980                 rss << result.getMessage() << '\n';
16981             for( auto const& msg : stats.infoMessages )
16982                 if( msg.type == ResultWas::Info )
16983                     rss << msg.message << '\n';
16984 
16985             rss << "at " << result.getSourceInfo();
16986             xml.writeText( rss.str(), XmlFormatting::Newline );
16987         }
16988     }
16989 
16990     CATCH_REGISTER_REPORTER( "junit", JunitReporter )
16991 
16992 } // end namespace Catch
16993 // end catch_reporter_junit.cpp
16994 // start catch_reporter_listening.cpp
16995 
16996 #include <cassert>
16997 
16998 namespace Catch {
16999 
ListeningReporter()17000     ListeningReporter::ListeningReporter() {
17001         // We will assume that listeners will always want all assertions
17002         m_preferences.shouldReportAllAssertions = true;
17003     }
17004 
addListener(IStreamingReporterPtr && listener)17005     void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17006         m_listeners.push_back( std::move( listener ) );
17007     }
17008 
addReporter(IStreamingReporterPtr && reporter)17009     void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17010         assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17011         m_reporter = std::move( reporter );
17012         m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17013     }
17014 
getPreferences() const17015     ReporterPreferences ListeningReporter::getPreferences() const {
17016         return m_preferences;
17017     }
17018 
getSupportedVerbosities()17019     std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17020         return std::set<Verbosity>{ };
17021     }
17022 
noMatchingTestCases(std::string const & spec)17023     void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
17024         for ( auto const& listener : m_listeners ) {
17025             listener->noMatchingTestCases( spec );
17026         }
17027         m_reporter->noMatchingTestCases( spec );
17028     }
17029 
reportInvalidArguments(std::string const & arg)17030     void ListeningReporter::reportInvalidArguments(std::string const&arg){
17031         for ( auto const& listener : m_listeners ) {
17032             listener->reportInvalidArguments( arg );
17033         }
17034         m_reporter->reportInvalidArguments( arg );
17035     }
17036 
17037 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)17038     void ListeningReporter::benchmarkPreparing( std::string const& name ) {
17039 		for (auto const& listener : m_listeners) {
17040 			listener->benchmarkPreparing(name);
17041 		}
17042 		m_reporter->benchmarkPreparing(name);
17043 	}
benchmarkStarting(BenchmarkInfo const & benchmarkInfo)17044     void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
17045         for ( auto const& listener : m_listeners ) {
17046             listener->benchmarkStarting( benchmarkInfo );
17047         }
17048         m_reporter->benchmarkStarting( benchmarkInfo );
17049     }
benchmarkEnded(BenchmarkStats<> const & benchmarkStats)17050     void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
17051         for ( auto const& listener : m_listeners ) {
17052             listener->benchmarkEnded( benchmarkStats );
17053         }
17054         m_reporter->benchmarkEnded( benchmarkStats );
17055     }
17056 
benchmarkFailed(std::string const & error)17057 	void ListeningReporter::benchmarkFailed( std::string const& error ) {
17058 		for (auto const& listener : m_listeners) {
17059 			listener->benchmarkFailed(error);
17060 		}
17061 		m_reporter->benchmarkFailed(error);
17062 	}
17063 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17064 
testRunStarting(TestRunInfo const & testRunInfo)17065     void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
17066         for ( auto const& listener : m_listeners ) {
17067             listener->testRunStarting( testRunInfo );
17068         }
17069         m_reporter->testRunStarting( testRunInfo );
17070     }
17071 
testGroupStarting(GroupInfo const & groupInfo)17072     void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17073         for ( auto const& listener : m_listeners ) {
17074             listener->testGroupStarting( groupInfo );
17075         }
17076         m_reporter->testGroupStarting( groupInfo );
17077     }
17078 
testCaseStarting(TestCaseInfo const & testInfo)17079     void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17080         for ( auto const& listener : m_listeners ) {
17081             listener->testCaseStarting( testInfo );
17082         }
17083         m_reporter->testCaseStarting( testInfo );
17084     }
17085 
sectionStarting(SectionInfo const & sectionInfo)17086     void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17087         for ( auto const& listener : m_listeners ) {
17088             listener->sectionStarting( sectionInfo );
17089         }
17090         m_reporter->sectionStarting( sectionInfo );
17091     }
17092 
assertionStarting(AssertionInfo const & assertionInfo)17093     void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
17094         for ( auto const& listener : m_listeners ) {
17095             listener->assertionStarting( assertionInfo );
17096         }
17097         m_reporter->assertionStarting( assertionInfo );
17098     }
17099 
17100     // The return value indicates if the messages buffer should be cleared:
assertionEnded(AssertionStats const & assertionStats)17101     bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
17102         for( auto const& listener : m_listeners ) {
17103             static_cast<void>( listener->assertionEnded( assertionStats ) );
17104         }
17105         return m_reporter->assertionEnded( assertionStats );
17106     }
17107 
sectionEnded(SectionStats const & sectionStats)17108     void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
17109         for ( auto const& listener : m_listeners ) {
17110             listener->sectionEnded( sectionStats );
17111         }
17112         m_reporter->sectionEnded( sectionStats );
17113     }
17114 
testCaseEnded(TestCaseStats const & testCaseStats)17115     void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17116         for ( auto const& listener : m_listeners ) {
17117             listener->testCaseEnded( testCaseStats );
17118         }
17119         m_reporter->testCaseEnded( testCaseStats );
17120     }
17121 
testGroupEnded(TestGroupStats const & testGroupStats)17122     void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17123         for ( auto const& listener : m_listeners ) {
17124             listener->testGroupEnded( testGroupStats );
17125         }
17126         m_reporter->testGroupEnded( testGroupStats );
17127     }
17128 
testRunEnded(TestRunStats const & testRunStats)17129     void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
17130         for ( auto const& listener : m_listeners ) {
17131             listener->testRunEnded( testRunStats );
17132         }
17133         m_reporter->testRunEnded( testRunStats );
17134     }
17135 
skipTest(TestCaseInfo const & testInfo)17136     void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
17137         for ( auto const& listener : m_listeners ) {
17138             listener->skipTest( testInfo );
17139         }
17140         m_reporter->skipTest( testInfo );
17141     }
17142 
isMulti() const17143     bool ListeningReporter::isMulti() const {
17144         return true;
17145     }
17146 
17147 } // end namespace Catch
17148 // end catch_reporter_listening.cpp
17149 // start catch_reporter_xml.cpp
17150 
17151 #if defined(_MSC_VER)
17152 #pragma warning(push)
17153 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
17154                               // Note that 4062 (not all labels are handled
17155                               // and default is missing) is enabled
17156 #endif
17157 
17158 namespace Catch {
XmlReporter(ReporterConfig const & _config)17159     XmlReporter::XmlReporter( ReporterConfig const& _config )
17160     :   StreamingReporterBase( _config ),
17161         m_xml(_config.stream())
17162     {
17163         m_reporterPrefs.shouldRedirectStdOut = true;
17164         m_reporterPrefs.shouldReportAllAssertions = true;
17165     }
17166 
17167     XmlReporter::~XmlReporter() = default;
17168 
getDescription()17169     std::string XmlReporter::getDescription() {
17170         return "Reports test results as an XML document";
17171     }
17172 
getStylesheetRef() const17173     std::string XmlReporter::getStylesheetRef() const {
17174         return std::string();
17175     }
17176 
writeSourceInfo(SourceLineInfo const & sourceInfo)17177     void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
17178         m_xml
17179             .writeAttribute( "filename", sourceInfo.file )
17180             .writeAttribute( "line", sourceInfo.line );
17181     }
17182 
noMatchingTestCases(std::string const & s)17183     void XmlReporter::noMatchingTestCases( std::string const& s ) {
17184         StreamingReporterBase::noMatchingTestCases( s );
17185     }
17186 
testRunStarting(TestRunInfo const & testInfo)17187     void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
17188         StreamingReporterBase::testRunStarting( testInfo );
17189         std::string stylesheetRef = getStylesheetRef();
17190         if( !stylesheetRef.empty() )
17191             m_xml.writeStylesheetRef( stylesheetRef );
17192         m_xml.startElement( "Catch" );
17193         if( !m_config->name().empty() )
17194             m_xml.writeAttribute( "name", m_config->name() );
17195         if (m_config->testSpec().hasFilters())
17196             m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
17197         if( m_config->rngSeed() != 0 )
17198             m_xml.scopedElement( "Randomness" )
17199                 .writeAttribute( "seed", m_config->rngSeed() );
17200     }
17201 
testGroupStarting(GroupInfo const & groupInfo)17202     void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17203         StreamingReporterBase::testGroupStarting( groupInfo );
17204         m_xml.startElement( "Group" )
17205             .writeAttribute( "name", groupInfo.name );
17206     }
17207 
testCaseStarting(TestCaseInfo const & testInfo)17208     void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17209         StreamingReporterBase::testCaseStarting(testInfo);
17210         m_xml.startElement( "TestCase" )
17211             .writeAttribute( "name", trim( testInfo.name ) )
17212             .writeAttribute( "description", testInfo.description )
17213             .writeAttribute( "tags", testInfo.tagsAsString() );
17214 
17215         writeSourceInfo( testInfo.lineInfo );
17216 
17217         if ( m_config->showDurations() == ShowDurations::Always )
17218             m_testCaseTimer.start();
17219         m_xml.ensureTagClosed();
17220     }
17221 
sectionStarting(SectionInfo const & sectionInfo)17222     void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17223         StreamingReporterBase::sectionStarting( sectionInfo );
17224         if( m_sectionDepth++ > 0 ) {
17225             m_xml.startElement( "Section" )
17226                 .writeAttribute( "name", trim( sectionInfo.name ) );
17227             writeSourceInfo( sectionInfo.lineInfo );
17228             m_xml.ensureTagClosed();
17229         }
17230     }
17231 
assertionStarting(AssertionInfo const &)17232     void XmlReporter::assertionStarting( AssertionInfo const& ) { }
17233 
assertionEnded(AssertionStats const & assertionStats)17234     bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
17235 
17236         AssertionResult const& result = assertionStats.assertionResult;
17237 
17238         bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17239 
17240         if( includeResults || result.getResultType() == ResultWas::Warning ) {
17241             // Print any info messages in <Info> tags.
17242             for( auto const& msg : assertionStats.infoMessages ) {
17243                 if( msg.type == ResultWas::Info && includeResults ) {
17244                     m_xml.scopedElement( "Info" )
17245                             .writeText( msg.message );
17246                 } else if ( msg.type == ResultWas::Warning ) {
17247                     m_xml.scopedElement( "Warning" )
17248                             .writeText( msg.message );
17249                 }
17250             }
17251         }
17252 
17253         // Drop out if result was successful but we're not printing them.
17254         if( !includeResults && result.getResultType() != ResultWas::Warning )
17255             return true;
17256 
17257         // Print the expression if there is one.
17258         if( result.hasExpression() ) {
17259             m_xml.startElement( "Expression" )
17260                 .writeAttribute( "success", result.succeeded() )
17261                 .writeAttribute( "type", result.getTestMacroName() );
17262 
17263             writeSourceInfo( result.getSourceInfo() );
17264 
17265             m_xml.scopedElement( "Original" )
17266                 .writeText( result.getExpression() );
17267             m_xml.scopedElement( "Expanded" )
17268                 .writeText( result.getExpandedExpression() );
17269         }
17270 
17271         // And... Print a result applicable to each result type.
17272         switch( result.getResultType() ) {
17273             case ResultWas::ThrewException:
17274                 m_xml.startElement( "Exception" );
17275                 writeSourceInfo( result.getSourceInfo() );
17276                 m_xml.writeText( result.getMessage() );
17277                 m_xml.endElement();
17278                 break;
17279             case ResultWas::FatalErrorCondition:
17280                 m_xml.startElement( "FatalErrorCondition" );
17281                 writeSourceInfo( result.getSourceInfo() );
17282                 m_xml.writeText( result.getMessage() );
17283                 m_xml.endElement();
17284                 break;
17285             case ResultWas::Info:
17286                 m_xml.scopedElement( "Info" )
17287                     .writeText( result.getMessage() );
17288                 break;
17289             case ResultWas::Warning:
17290                 // Warning will already have been written
17291                 break;
17292             case ResultWas::ExplicitFailure:
17293                 m_xml.startElement( "Failure" );
17294                 writeSourceInfo( result.getSourceInfo() );
17295                 m_xml.writeText( result.getMessage() );
17296                 m_xml.endElement();
17297                 break;
17298             default:
17299                 break;
17300         }
17301 
17302         if( result.hasExpression() )
17303             m_xml.endElement();
17304 
17305         return true;
17306     }
17307 
sectionEnded(SectionStats const & sectionStats)17308     void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
17309         StreamingReporterBase::sectionEnded( sectionStats );
17310         if( --m_sectionDepth > 0 ) {
17311             XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
17312             e.writeAttribute( "successes", sectionStats.assertions.passed );
17313             e.writeAttribute( "failures", sectionStats.assertions.failed );
17314             e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
17315 
17316             if ( m_config->showDurations() == ShowDurations::Always )
17317                 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
17318 
17319             m_xml.endElement();
17320         }
17321     }
17322 
testCaseEnded(TestCaseStats const & testCaseStats)17323     void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17324         StreamingReporterBase::testCaseEnded( testCaseStats );
17325         XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
17326         e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
17327 
17328         if ( m_config->showDurations() == ShowDurations::Always )
17329             e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17330 
17331         if( !testCaseStats.stdOut.empty() )
17332             m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17333         if( !testCaseStats.stdErr.empty() )
17334             m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17335 
17336         m_xml.endElement();
17337     }
17338 
testGroupEnded(TestGroupStats const & testGroupStats)17339     void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17340         StreamingReporterBase::testGroupEnded( testGroupStats );
17341         // TODO: Check testGroupStats.aborting and act accordingly.
17342         m_xml.scopedElement( "OverallResults" )
17343             .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
17344             .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
17345             .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
17346         m_xml.scopedElement( "OverallResultsCases")
17347             .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
17348             .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
17349             .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
17350         m_xml.endElement();
17351     }
17352 
testRunEnded(TestRunStats const & testRunStats)17353     void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
17354         StreamingReporterBase::testRunEnded( testRunStats );
17355         m_xml.scopedElement( "OverallResults" )
17356             .writeAttribute( "successes", testRunStats.totals.assertions.passed )
17357             .writeAttribute( "failures", testRunStats.totals.assertions.failed )
17358             .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
17359         m_xml.scopedElement( "OverallResultsCases")
17360             .writeAttribute( "successes", testRunStats.totals.testCases.passed )
17361             .writeAttribute( "failures", testRunStats.totals.testCases.failed )
17362             .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
17363         m_xml.endElement();
17364     }
17365 
17366 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
benchmarkPreparing(std::string const & name)17367     void XmlReporter::benchmarkPreparing(std::string const& name) {
17368         m_xml.startElement("BenchmarkResults")
17369             .writeAttribute("name", name);
17370     }
17371 
benchmarkStarting(BenchmarkInfo const & info)17372     void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
17373         m_xml.writeAttribute("samples", info.samples)
17374             .writeAttribute("resamples", info.resamples)
17375             .writeAttribute("iterations", info.iterations)
17376             .writeAttribute("clockResolution", info.clockResolution)
17377             .writeAttribute("estimatedDuration", info.estimatedDuration)
17378             .writeComment("All values in nano seconds");
17379     }
17380 
benchmarkEnded(BenchmarkStats<> const & benchmarkStats)17381     void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17382         m_xml.startElement("mean")
17383             .writeAttribute("value", benchmarkStats.mean.point.count())
17384             .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17385             .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17386             .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17387         m_xml.endElement();
17388         m_xml.startElement("standardDeviation")
17389             .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17390             .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17391             .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17392             .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17393         m_xml.endElement();
17394         m_xml.startElement("outliers")
17395             .writeAttribute("variance", benchmarkStats.outlierVariance)
17396             .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17397             .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17398             .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17399             .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17400         m_xml.endElement();
17401         m_xml.endElement();
17402     }
17403 
benchmarkFailed(std::string const & error)17404     void XmlReporter::benchmarkFailed(std::string const &error) {
17405         m_xml.scopedElement("failed").
17406             writeAttribute("message", error);
17407         m_xml.endElement();
17408     }
17409 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17410 
17411     CATCH_REGISTER_REPORTER( "xml", XmlReporter )
17412 
17413 } // end namespace Catch
17414 
17415 #if defined(_MSC_VER)
17416 #pragma warning(pop)
17417 #endif
17418 // end catch_reporter_xml.cpp
17419 
17420 namespace Catch {
17421     LeakDetector leakDetector;
17422 }
17423 
17424 #ifdef __clang__
17425 #pragma clang diagnostic pop
17426 #endif
17427 
17428 // end catch_impl.hpp
17429 #endif
17430 
17431 #ifdef CATCH_CONFIG_MAIN
17432 // start catch_default_main.hpp
17433 
17434 #ifndef __OBJC__
17435 
17436 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17437 // Standard C/C++ Win32 Unicode wmain entry point
wmain(int argc,wchar_t * argv[],wchar_t * [])17438 extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
17439 #else
17440 // Standard C/C++ main entry point
17441 int main (int argc, char * argv[]) {
17442 #endif
17443 
17444     return Catch::Session().run( argc, argv );
17445 }
17446 
17447 #else // __OBJC__
17448 
17449 // Objective-C entry point
17450 int main (int argc, char * const argv[]) {
17451 #if !CATCH_ARC_ENABLED
17452     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17453 #endif
17454 
17455     Catch::registerTestMethods();
17456     int result = Catch::Session().run( argc, (char**)argv );
17457 
17458 #if !CATCH_ARC_ENABLED
17459     [pool drain];
17460 #endif
17461 
17462     return result;
17463 }
17464 
17465 #endif // __OBJC__
17466 
17467 // end catch_default_main.hpp
17468 #endif
17469 
17470 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17471 
17472 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17473 #  undef CLARA_CONFIG_MAIN
17474 #endif
17475 
17476 #if !defined(CATCH_CONFIG_DISABLE)
17477 //////
17478 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17479 #ifdef CATCH_CONFIG_PREFIX_ALL
17480 
17481 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17482 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17483 
17484 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17485 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17486 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17487 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17488 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17489 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17490 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17491 
17492 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17493 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17494 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17495 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17496 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17497 
17498 #define CATCH_CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17499 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17500 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17501 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17502 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17503 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17504 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17505 
17506 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17507 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17508 
17509 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17510 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17511 
17512 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17513 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17514 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17515 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17516 
17517 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17518 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17519 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17520 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17521 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17522 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17523 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17524 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17525 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17526 
17527 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17528 
17529 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17530 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17531 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17532 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17533 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17534 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17535 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17536 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17537 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17538 #else
17539 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17540 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17541 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17542 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17543 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17544 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17545 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17546 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17547 #endif
17548 
17549 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17550 #define CATCH_STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__ ,      #__VA_ARGS__ );     CATCH_SUCCEED( #__VA_ARGS__ )
17551 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17552 #else
17553 #define CATCH_STATIC_REQUIRE( ... )       CATCH_REQUIRE( __VA_ARGS__ )
17554 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17555 #endif
17556 
17557 // "BDD-style" convenience wrappers
17558 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17559 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17560 #define CATCH_GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( "    Given: " << desc )
17561 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17562 #define CATCH_WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     When: " << desc )
17563 #define CATCH_AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17564 #define CATCH_THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     Then: " << desc )
17565 #define CATCH_AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( "      And: " << desc )
17566 
17567 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17568 #define CATCH_BENCHMARK(...) \
17569     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__,,))
17570 #define CATCH_BENCHMARK_ADVANCED(name) \
17571     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17572 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17573 
17574 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17575 #else
17576 
17577 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__  )
17578 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17579 
17580 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17581 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17582 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17583 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17584 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17585 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17586 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17587 
17588 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17589 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17590 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17591 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17592 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17593 
17594 #define CHECK_THROWS( ... )  INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17595 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17596 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17597 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17598 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17599 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17600 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17601 
17602 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17603 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17604 
17605 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17606 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17607 
17608 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17609 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17610 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17611 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17612 
17613 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17614 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17615 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17616 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17617 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17618 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17619 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17620 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17621 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17622 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17623 
17624 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17625 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17626 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17627 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17628 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17629 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17630 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17631 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17632 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17633 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17634 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17635 #else
17636 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17637 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17638 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17639 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17640 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17641 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17642 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17643 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17644 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17645 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17646 #endif
17647 
17648 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17649 #define STATIC_REQUIRE( ... )       static_assert(   __VA_ARGS__,  #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17650 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17651 #else
17652 #define STATIC_REQUIRE( ... )       REQUIRE( __VA_ARGS__ )
17653 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17654 #endif
17655 
17656 #endif
17657 
17658 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17659 
17660 // "BDD-style" convenience wrappers
17661 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17662 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17663 
17664 #define GIVEN( desc )     INTERNAL_CATCH_DYNAMIC_SECTION( "    Given: " << desc )
17665 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17666 #define WHEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     When: " << desc )
17667 #define AND_WHEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17668 #define THEN( desc )      INTERNAL_CATCH_DYNAMIC_SECTION( "     Then: " << desc )
17669 #define AND_THEN( desc )  INTERNAL_CATCH_DYNAMIC_SECTION( "      And: " << desc )
17670 
17671 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17672 #define BENCHMARK(...) \
17673     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__,,))
17674 #define BENCHMARK_ADVANCED(name) \
17675     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17676 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17677 
17678 using Catch::Detail::Approx;
17679 
17680 #else // CATCH_CONFIG_DISABLE
17681 
17682 //////
17683 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17684 #ifdef CATCH_CONFIG_PREFIX_ALL
17685 
17686 #define CATCH_REQUIRE( ... )        (void)(0)
17687 #define CATCH_REQUIRE_FALSE( ... )  (void)(0)
17688 
17689 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17690 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17691 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher )     (void)(0)
17692 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17693 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17694 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17695 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17696 
17697 #define CATCH_CHECK( ... )         (void)(0)
17698 #define CATCH_CHECK_FALSE( ... )   (void)(0)
17699 #define CATCH_CHECKED_IF( ... )    if (__VA_ARGS__)
17700 #define CATCH_CHECKED_ELSE( ... )  if (!(__VA_ARGS__))
17701 #define CATCH_CHECK_NOFAIL( ... )  (void)(0)
17702 
17703 #define CATCH_CHECK_THROWS( ... )  (void)(0)
17704 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17705 #define CATCH_CHECK_THROWS_WITH( expr, matcher )     (void)(0)
17706 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17707 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17708 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17709 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17710 
17711 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17712 #define CATCH_CHECK_THAT( arg, matcher )   (void)(0)
17713 
17714 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17715 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17716 
17717 #define CATCH_INFO( msg )          (void)(0)
17718 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17719 #define CATCH_WARN( msg )          (void)(0)
17720 #define CATCH_CAPTURE( msg )       (void)(0)
17721 
17722 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17723 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17724 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
17725 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17726 #define CATCH_SECTION( ... )
17727 #define CATCH_DYNAMIC_SECTION( ... )
17728 #define CATCH_FAIL( ... ) (void)(0)
17729 #define CATCH_FAIL_CHECK( ... ) (void)(0)
17730 #define CATCH_SUCCEED( ... ) (void)(0)
17731 
17732 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17733 
17734 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17735 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17736 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17737 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17738 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17739 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17740 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17741 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17742 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17743 #else
17744 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17745 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17746 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17747 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17748 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17749 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17750 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17751 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17752 #endif
17753 
17754 // "BDD-style" convenience wrappers
17755 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17756 #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 )
17757 #define CATCH_GIVEN( desc )
17758 #define CATCH_AND_GIVEN( desc )
17759 #define CATCH_WHEN( desc )
17760 #define CATCH_AND_WHEN( desc )
17761 #define CATCH_THEN( desc )
17762 #define CATCH_AND_THEN( desc )
17763 
17764 #define CATCH_STATIC_REQUIRE( ... )       (void)(0)
17765 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17766 
17767 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17768 #else
17769 
17770 #define REQUIRE( ... )       (void)(0)
17771 #define REQUIRE_FALSE( ... ) (void)(0)
17772 
17773 #define REQUIRE_THROWS( ... ) (void)(0)
17774 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17775 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17776 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17777 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17778 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17779 #define REQUIRE_NOTHROW( ... ) (void)(0)
17780 
17781 #define CHECK( ... ) (void)(0)
17782 #define CHECK_FALSE( ... ) (void)(0)
17783 #define CHECKED_IF( ... ) if (__VA_ARGS__)
17784 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17785 #define CHECK_NOFAIL( ... ) (void)(0)
17786 
17787 #define CHECK_THROWS( ... )  (void)(0)
17788 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17789 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17790 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17791 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17792 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17793 #define CHECK_NOTHROW( ... ) (void)(0)
17794 
17795 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17796 #define CHECK_THAT( arg, matcher ) (void)(0)
17797 
17798 #define REQUIRE_THAT( arg, matcher ) (void)(0)
17799 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17800 
17801 #define INFO( msg ) (void)(0)
17802 #define UNSCOPED_INFO( msg ) (void)(0)
17803 #define WARN( msg ) (void)(0)
17804 #define CAPTURE( msg ) (void)(0)
17805 
17806 #define TEST_CASE( ... )  INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17807 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17808 #define METHOD_AS_TEST_CASE( method, ... )
17809 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17810 #define SECTION( ... )
17811 #define DYNAMIC_SECTION( ... )
17812 #define FAIL( ... ) (void)(0)
17813 #define FAIL_CHECK( ... ) (void)(0)
17814 #define SUCCEED( ... ) (void)(0)
17815 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17816 
17817 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17818 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17819 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17820 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17821 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17822 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17823 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17824 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17825 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17826 #else
17827 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17828 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17829 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17830 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17831 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17832 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17833 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17834 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17835 #endif
17836 
17837 #define STATIC_REQUIRE( ... )       (void)(0)
17838 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17839 
17840 #endif
17841 
17842 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17843 
17844 // "BDD-style" convenience wrappers
17845 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17846 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17847 
17848 #define GIVEN( desc )
17849 #define AND_GIVEN( desc )
17850 #define WHEN( desc )
17851 #define AND_WHEN( desc )
17852 #define THEN( desc )
17853 #define AND_THEN( desc )
17854 
17855 using Catch::Detail::Approx;
17856 
17857 #endif
17858 
17859 #endif // ! CATCH_CONFIG_IMPL_ONLY
17860 
17861 // start catch_reenable_warnings.h
17862 
17863 
17864 #ifdef __clang__
17865 #    ifdef __ICC // icpc defines the __clang__ macro
17866 #        pragma warning(pop)
17867 #    else
17868 #        pragma clang diagnostic pop
17869 #    endif
17870 #elif defined __GNUC__
17871 #    pragma GCC diagnostic pop
17872 #endif
17873 
17874 // end catch_reenable_warnings.h
17875 // end catch.hpp
17876 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
17877 
17878