Update rive-cpp to 2.0 version
[platform/core/uifw/rive-tizen.git] / submodule / rive-cpp / dev / test / include / catch.hpp
1 /*
2  *  Catch v2.13.7
3  *  Generated: 2021-07-28 20:29:27.753164
4  *  ----------------------------------------------------------
5  *  This file has been merged from multiple headers. Please don't edit it
6  * directly Copyright (c) 2021 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 #define CATCH_VERSION_MAJOR 2
16 #define CATCH_VERSION_MINOR 13
17 #define CATCH_VERSION_PATCH 7
18
19 #ifdef __clang__
20 #pragma clang system_header
21 #elif defined __GNUC__
22 #pragma GCC system_header
23 #endif
24
25 // start catch_suppress_warnings.h
26
27 #ifdef __clang__
28 #ifdef __ICC // icpc defines the __clang__ macro
29 #pragma warning(push)
30 #pragma warning(disable : 161 1682)
31 #else // __ICC
32 #pragma clang diagnostic push
33 #pragma clang diagnostic ignored "-Wpadded"
34 #pragma clang diagnostic ignored "-Wswitch-enum"
35 #pragma clang diagnostic ignored "-Wcovered-switch-default"
36 #endif
37 #elif defined __GNUC__
38 // Because REQUIREs trigger GCC's -Wparentheses, and because still
39 // supported version of g++ have only buggy support for _Pragmas,
40 // Wparentheses have to be suppressed globally.
41 #pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
42
43 #pragma GCC diagnostic push
44 #pragma GCC diagnostic ignored "-Wunused-variable"
45 #pragma GCC diagnostic ignored "-Wpadded"
46 #endif
47 // end catch_suppress_warnings.h
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
49 #define CATCH_IMPL
50 #define CATCH_CONFIG_ALL_PARTS
51 #endif
52
53 // In the impl file, we want to have access to all parts of the headers
54 // Can also be used to sanely support PCHs
55 #if defined(CATCH_CONFIG_ALL_PARTS)
56 #define CATCH_CONFIG_EXTERNAL_INTERFACES
57 #if defined(CATCH_CONFIG_DISABLE_MATCHERS)
58 #undef CATCH_CONFIG_DISABLE_MATCHERS
59 #endif
60 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
62 #endif
63 #endif
64
65 #if !defined(CATCH_CONFIG_IMPL_ONLY)
66 // start catch_platform.h
67
68 // See e.g.:
69 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
70 #ifdef __APPLE__
71 #include <TargetConditionals.h>
72 #if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
73 #define CATCH_PLATFORM_MAC
74 #elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
75 #define CATCH_PLATFORM_IPHONE
76 #endif
77
78 #elif defined(linux) || defined(__linux) || defined(__linux__)
79 #define CATCH_PLATFORM_LINUX
80
81 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ||              \
82     defined(__MINGW32__)
83 #define CATCH_PLATFORM_WINDOWS
84 #endif
85
86 // end catch_platform.h
87
88 #ifdef CATCH_IMPL
89 #ifndef CLARA_CONFIG_MAIN
90 #define CLARA_CONFIG_MAIN_NOT_DEFINED
91 #define CLARA_CONFIG_MAIN
92 #endif
93 #endif
94
95 // start catch_user_interfaces.h
96
97 namespace Catch {
98     unsigned int rngSeed();
99 }
100
101 // end catch_user_interfaces.h
102 // start catch_tag_alias_autoregistrar.h
103
104 // start catch_common.h
105
106 // start catch_compiler_capabilities.h
107
108 // Detect a number of compiler features - by compiler
109 // The following features are defined:
110 //
111 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
112 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
113 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
114 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
115 // ****************
116 // Note to maintainers: if new toggles are added please document them
117 // in configuration.md, too
118 // ****************
119
120 // In general each macro has a _NO_<feature name> form
121 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
122 // Many features, at point of detection, define an _INTERNAL_ macro, so they
123 // can be combined, en-mass, with the _NO_ forms later.
124
125 #ifdef __cplusplus
126
127 #if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
128 #define CATCH_CPP14_OR_GREATER
129 #endif
130
131 #if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
132 #define CATCH_CPP17_OR_GREATER
133 #endif
134
135 #endif
136
137 // Only GCC compiler should be used in this block, so other compilers trying to
138 // mask themselves as GCC should be ignored.
139 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) &&         \
140     !defined(__LCC__)
141 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic push")
142 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("GCC diagnostic pop")
143
144 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
145
146 #endif
147
148 #if defined(__clang__)
149
150 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma("clang diagnostic push")
151 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma("clang diagnostic pop")
152
153 // As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
154 // which results in calls to destructors being emitted for each temporary,
155 // without a matching initialization. In practice, this can result in something
156 // like `std::string::~string` being called on an uninitialized value.
157 //
158 // For example, this code will likely segfault under IBM XL:
159 // ```
160 // REQUIRE(std::string("12") + "34" == "1234")
161 // ```
162 //
163 // Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
164 #if !defined(__ibmxl__) && !defined(__CUDACC__)
165 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...)                                                        \
166     (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg,           \
167                                                hicpp-vararg) */
168 #endif
169
170 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                   \
171     _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"")                                \
172         _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
173
174 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS                                               \
175     _Pragma("clang diagnostic ignored \"-Wparentheses\"")
176
177 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS                                                    \
178     _Pragma("clang diagnostic ignored \"-Wunused-variable\"")
179
180 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                                             \
181     _Pragma("clang diagnostic ignored "                                                            \
182             "\"-Wgnu-zero-variadic-macro-arguments\"")
183
184 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                           \
185     _Pragma("clang diagnostic ignored \"-Wunused-template\"")
186
187 #endif // __clang__
188
189 ////////////////////////////////////////////////////////////////////////////////
190 // Assume that non-Windows platforms support posix signals by default
191 #if !defined(CATCH_PLATFORM_WINDOWS)
192 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
193 #endif
194
195 ////////////////////////////////////////////////////////////////////////////////
196 // We know some environments not to support full POSIX signals
197 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
198 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
199 #endif
200
201 #ifdef __OS400__
202 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
203 #define CATCH_CONFIG_COLOUR_NONE
204 #endif
205
206 ////////////////////////////////////////////////////////////////////////////////
207 // Android somehow still does not support std::to_string
208 #if defined(__ANDROID__)
209 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
210 #define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
211 #endif
212
213 ////////////////////////////////////////////////////////////////////////////////
214 // Not all Windows environments support SEH properly
215 #if defined(__MINGW32__)
216 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
217 #endif
218
219 ////////////////////////////////////////////////////////////////////////////////
220 // PS4
221 #if defined(__ORBIS__)
222 #define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
223 #endif
224
225 ////////////////////////////////////////////////////////////////////////////////
226 // Cygwin
227 #ifdef __CYGWIN__
228
229 // Required for some versions of Cygwin to declare gettimeofday
230 // see:
231 // http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
232 #define _BSD_SOURCE
233 // some versions of cygwin (most) do not support std::to_string. Use the libstd
234 // check.
235 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html
236 // line 2812-2813
237 #if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) &&                                     \
238       !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
239
240 #define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
241
242 #endif
243 #endif // __CYGWIN__
244
245 ////////////////////////////////////////////////////////////////////////////////
246 // Visual C++
247 #if defined(_MSC_VER)
248
249 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push))
250 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop))
251
252 // Universal Windows platform does not support SEH
253 // Or console colours (or console at all...)
254 #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
255 #define CATCH_CONFIG_COLOUR_NONE
256 #else
257 #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
258 #endif
259
260 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
261 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
262 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
263 #if !defined(__clang__) // Handle Clang masquerading for msvc
264 #if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
265 #define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
266 #endif // MSVC_TRADITIONAL
267 #endif // __clang__
268
269 #endif // _MSC_VER
270
271 #if defined(_REENTRANT) || defined(_MSC_VER)
272 // Enable async processing, as -pthread is specified or no additional linking is
273 // required
274 #define CATCH_INTERNAL_CONFIG_USE_ASYNC
275 #endif // _MSC_VER
276
277 ////////////////////////////////////////////////////////////////////////////////
278 // Check if we are compiled with -fno-exceptions or equivalent
279 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
280 #define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
281 #endif
282
283 ////////////////////////////////////////////////////////////////////////////////
284 // DJGPP
285 #ifdef __DJGPP__
286 #define CATCH_INTERNAL_CONFIG_NO_WCHAR
287 #endif // __DJGPP__
288
289 ////////////////////////////////////////////////////////////////////////////////
290 // Embarcadero C++Build
291 #if defined(__BORLANDC__)
292 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
293 #endif
294
295 ////////////////////////////////////////////////////////////////////////////////
296
297 // Use of __COUNTER__ is suppressed during code analysis in
298 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
299 // handled by it.
300 // Otherwise all supported compilers support COUNTER macro,
301 // but user still might want to turn it off
302 #if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
303 #define CATCH_INTERNAL_CONFIG_COUNTER
304 #endif
305
306 ////////////////////////////////////////////////////////////////////////////////
307
308 // RTX is a special version of Windows that is real time.
309 // This means that it is detected as Windows, but does not provide
310 // the same set of capabilities as real Windows does.
311 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
312 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
313 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
314 #define CATCH_CONFIG_COLOUR_NONE
315 #endif
316
317 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
318 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
319 #endif
320
321 // Various stdlib support checks that require __has_include
322 #if defined(__has_include)
323 // Check if string_view is available and usable
324 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
325 #define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
326 #endif
327
328 // Check if optional is available and usable
329 #if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
330 #define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
331 #endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
332
333 // Check if byte is available and usable
334 #if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
335 #include <cstddef>
336 #if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
337 #define CATCH_INTERNAL_CONFIG_CPP17_BYTE
338 #endif
339 #endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
340
341 // Check if variant is available and usable
342 #if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
343 #if defined(__clang__) && (__clang_major__ < 8)
344 // work around clang bug with libstdc++
345 // https://bugs.llvm.org/show_bug.cgi?id=31852 fix should be in clang 8,
346 // workaround in libstdc++ 8.2
347 #include <ciso646>
348 #if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
349 #define CATCH_CONFIG_NO_CPP17_VARIANT
350 #else
351 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
352 #endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE
353        // < 9)
354 #else
355 #define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
356 #endif // defined(__clang__) && (__clang_major__ < 8)
357 #endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
358 #endif // defined(__has_include)
359
360 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) &&                 \
361     !defined(CATCH_CONFIG_COUNTER)
362 #define CATCH_CONFIG_COUNTER
363 #endif
364 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) &&         \
365     !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
366 #define CATCH_CONFIG_WINDOWS_SEH
367 #endif
368 // This is set by default, because we assume that unix compilers are
369 // posix-signal-compatible by default.
370 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) &&                                                \
371     !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \
372     !defined(CATCH_CONFIG_POSIX_SIGNALS)
373 #define CATCH_CONFIG_POSIX_SIGNALS
374 #endif
375 // This is set by default, because we assume that compilers with no wchar_t
376 // support are just rare exceptions.
377 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) &&                 \
378     !defined(CATCH_CONFIG_WCHAR)
379 #define CATCH_CONFIG_WCHAR
380 #endif
381
382 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) &&                                          \
383     !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
384 #define CATCH_CONFIG_CPP11_TO_STRING
385 #endif
386
387 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) &&   \
388     !defined(CATCH_CONFIG_CPP17_OPTIONAL)
389 #define CATCH_CONFIG_CPP17_OPTIONAL
390 #endif
391
392 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) &&                                            \
393     !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
394 #define CATCH_CONFIG_CPP17_STRING_VIEW
395 #endif
396
397 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) &&     \
398     !defined(CATCH_CONFIG_CPP17_VARIANT)
399 #define CATCH_CONFIG_CPP17_VARIANT
400 #endif
401
402 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) &&           \
403     !defined(CATCH_CONFIG_CPP17_BYTE)
404 #define CATCH_CONFIG_CPP17_BYTE
405 #endif
406
407 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
408 #define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
409 #endif
410
411 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) &&                                                  \
412     !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) &&     \
413     !defined(CATCH_CONFIG_NEW_CAPTURE)
414 #define CATCH_CONFIG_NEW_CAPTURE
415 #endif
416
417 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
418 #define CATCH_CONFIG_DISABLE_EXCEPTIONS
419 #endif
420
421 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) &&   \
422     !defined(CATCH_CONFIG_POLYFILL_ISNAN)
423 #define CATCH_CONFIG_POLYFILL_ISNAN
424 #endif
425
426 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) &&        \
427     !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
428 #define CATCH_CONFIG_USE_ASYNC
429 #endif
430
431 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) &&                                             \
432     !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
433 #define CATCH_CONFIG_ANDROID_LOGWRITE
434 #endif
435
436 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) &&                                             \
437     !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
438 #define CATCH_CONFIG_GLOBAL_NEXTAFTER
439 #endif
440
441 // Even if we do not think the compiler has that warning, we still have
442 // to provide a macro that can be used by the code.
443 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
444 #define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
445 #endif
446 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
447 #define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
448 #endif
449 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
450 #define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
451 #endif
452 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
453 #define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
454 #endif
455 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
456 #define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
457 #endif
458 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
459 #define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
460 #endif
461
462 // The goal of this macro is to avoid evaluation of the arguments, but
463 // still have the compiler warn on problems inside...
464 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
465 #define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
466 #endif
467
468 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
469 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
470 #elif defined(__clang__) && (__clang_major__ < 5)
471 #undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
472 #endif
473
474 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
475 #define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
476 #endif
477
478 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
479 #define CATCH_TRY if ((true))
480 #define CATCH_CATCH_ALL if ((false))
481 #define CATCH_CATCH_ANON(type) if ((false))
482 #else
483 #define CATCH_TRY try
484 #define CATCH_CATCH_ALL catch (...)
485 #define CATCH_CATCH_ANON(type) catch (type)
486 #endif
487
488 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) &&                                \
489     !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) &&                                     \
490     !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
491 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
492 #endif
493
494 // end catch_compiler_capabilities.h
495 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
496 #define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line)
497 #ifdef CATCH_CONFIG_COUNTER
498 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__)
499 #else
500 #define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__)
501 #endif
502
503 #include <iosfwd>
504 #include <string>
505 #include <cstdint>
506
507 // We need a dummy global operator<< so we can bring it into Catch namespace
508 // later
509 struct Catch_global_namespace_dummy {};
510 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
511
512 namespace Catch {
513
514     struct CaseSensitive {
515         enum Choice { Yes, No };
516     };
517
518     class NonCopyable {
519         NonCopyable(NonCopyable const&) = delete;
520         NonCopyable(NonCopyable&&) = delete;
521         NonCopyable& operator=(NonCopyable const&) = delete;
522         NonCopyable& operator=(NonCopyable&&) = delete;
523
524     protected:
525         NonCopyable();
526         virtual ~NonCopyable();
527     };
528
529     struct SourceLineInfo {
530
531         SourceLineInfo() = delete;
532         SourceLineInfo(char const* _file, std::size_t _line) noexcept : file(_file), line(_line) {}
533
534         SourceLineInfo(SourceLineInfo const& other) = default;
535         SourceLineInfo& operator=(SourceLineInfo const&) = default;
536         SourceLineInfo(SourceLineInfo&&) noexcept = default;
537         SourceLineInfo& operator=(SourceLineInfo&&) noexcept = default;
538
539         bool empty() const noexcept { return file[0] == '\0'; }
540         bool operator==(SourceLineInfo const& other) const noexcept;
541         bool operator<(SourceLineInfo const& other) const noexcept;
542
543         char const* file;
544         std::size_t line;
545     };
546
547     std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info);
548
549     // Bring in operator<< from global namespace into Catch namespace
550     // This is necessary because the overload of operator<< above makes
551     // lookup stop at namespace Catch
552     using ::operator<<;
553
554     // Use this in variadic streaming macros to allow
555     //    >> +StreamEndStop
556     // as well as
557     //    >> stuff +StreamEndStop
558     struct StreamEndStop {
559         std::string operator+() const;
560     };
561     template <typename T> T const& operator+(T const& value, StreamEndStop) { return value; }
562 } // namespace Catch
563
564 #define CATCH_INTERNAL_LINEINFO                                                                    \
565     ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__))
566
567 // end catch_common.h
568 namespace Catch {
569
570     struct RegistrarForTagAliases {
571         RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo);
572     };
573
574 } // end namespace Catch
575
576 #define CATCH_REGISTER_TAG_ALIAS(alias, spec)                                                      \
577     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
578     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
579     namespace {                                                                                    \
580         Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)(            \
581             alias, spec, CATCH_INTERNAL_LINEINFO);                                                 \
582     }                                                                                              \
583     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
584
585 // end catch_tag_alias_autoregistrar.h
586 // start catch_test_registry.h
587
588 // start catch_interfaces_testcase.h
589
590 #include <vector>
591
592 namespace Catch {
593
594     class TestSpec;
595
596     struct ITestInvoker {
597         virtual void invoke() const = 0;
598         virtual ~ITestInvoker();
599     };
600
601     class TestCase;
602     struct IConfig;
603
604     struct ITestCaseRegistry {
605         virtual ~ITestCaseRegistry();
606         virtual std::vector<TestCase> const& getAllTests() const = 0;
607         virtual std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const = 0;
608     };
609
610     bool isThrowSafe(TestCase const& testCase, IConfig const& config);
611     bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
612     std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
613                                       TestSpec const& testSpec,
614                                       IConfig const& config);
615     std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
616
617 } // namespace Catch
618
619 // end catch_interfaces_testcase.h
620 // start catch_stringref.h
621
622 #include <cstddef>
623 #include <string>
624 #include <iosfwd>
625 #include <cassert>
626
627 namespace Catch {
628
629     /// A non-owning string class (similar to the forthcoming std::string_view)
630     /// Note that, because a StringRef may be a substring of another string,
631     /// it may not be null terminated.
632     class StringRef {
633     public:
634         using size_type = std::size_t;
635         using const_iterator = const char*;
636
637     private:
638         static constexpr char const* const s_empty = "";
639
640         char const* m_start = s_empty;
641         size_type m_size = 0;
642
643     public: // construction
644         constexpr StringRef() noexcept = default;
645
646         StringRef(char const* rawChars) noexcept;
647
648         constexpr StringRef(char const* rawChars, size_type size) noexcept :
649             m_start(rawChars), m_size(size) {}
650
651         StringRef(std::string const& stdString) noexcept :
652             m_start(stdString.c_str()), m_size(stdString.size()) {}
653
654         explicit operator std::string() const { return std::string(m_start, m_size); }
655
656     public: // operators
657         auto operator==(StringRef const& other) const noexcept -> bool;
658         auto operator!=(StringRef const& other) const noexcept -> bool { return !(*this == other); }
659
660         auto operator[](size_type index) const noexcept -> char {
661             assert(index < m_size);
662             return m_start[index];
663         }
664
665     public: // named queries
666         constexpr auto empty() const noexcept -> bool { return m_size == 0; }
667         constexpr auto size() const noexcept -> size_type { return m_size; }
668
669         // Returns the current start pointer. If the StringRef is not
670         // null-terminated, throws std::domain_exception
671         auto c_str() const -> char const*;
672
673     public: // substrings and searches
674         // Returns a substring of [start, start + length).
675         // If start + length > size(), then the substring is [start, size()).
676         // If start > size(), then the substring is empty.
677         auto substr(size_type start, size_type length) const noexcept -> StringRef;
678
679         // Returns the current start pointer. May not be null-terminated.
680         auto data() const noexcept -> char const*;
681
682         constexpr auto isNullTerminated() const noexcept -> bool { return m_start[m_size] == '\0'; }
683
684     public: // iterators
685         constexpr const_iterator begin() const { return m_start; }
686         constexpr const_iterator end() const { return m_start + m_size; }
687     };
688
689     auto operator+=(std::string& lhs, StringRef const& sr) -> std::string&;
690     auto operator<<(std::ostream& os, StringRef const& sr) -> std::ostream&;
691
692     constexpr auto operator"" _sr(char const* rawChars, std::size_t size) noexcept -> StringRef {
693         return StringRef(rawChars, size);
694     }
695 } // namespace Catch
696
697 constexpr auto operator"" _catch_sr(char const* rawChars, std::size_t size) noexcept
698     -> Catch::StringRef {
699     return Catch::StringRef(rawChars, size);
700 }
701
702 // end catch_stringref.h
703 // start catch_preprocessor.hpp
704
705 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
706 #define CATCH_RECURSION_LEVEL1(...)                                                                \
707     CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
708 #define CATCH_RECURSION_LEVEL2(...)                                                                \
709     CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
710 #define CATCH_RECURSION_LEVEL3(...)                                                                \
711     CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
712 #define CATCH_RECURSION_LEVEL4(...)                                                                \
713     CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
714 #define CATCH_RECURSION_LEVEL5(...)                                                                \
715     CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
716
717 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
718 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
719 // MSVC needs more evaluations
720 #define CATCH_RECURSION_LEVEL6(...)                                                                \
721     CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
722 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
723 #else
724 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
725 #endif
726
727 #define CATCH_REC_END(...)
728 #define CATCH_REC_OUT
729
730 #define CATCH_EMPTY()
731 #define CATCH_DEFER(id) id CATCH_EMPTY()
732
733 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
734 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
735 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
736 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
737 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0)
738 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
739
740 #define CATCH_REC_LIST0(f, x, peek, ...)                                                           \
741     , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
742 #define CATCH_REC_LIST1(f, x, peek, ...)                                                           \
743     , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))(f, peek, __VA_ARGS__)
744 #define CATCH_REC_LIST2(f, x, peek, ...)                                                           \
745     f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
746
747 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...)                                              \
748     , f(userdata, x)                                                                               \
749           CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
750 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...)                                              \
751     , f(userdata, x)                                                                               \
752           CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))(f, userdata, peek, __VA_ARGS__)
753 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...)                                              \
754     f(userdata, x)                                                                                 \
755         CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
756
757 // Applies the function macro `f` to each of the remaining parameters, inserts
758 // commas between the results, and passes userdata as the first parameter to
759 // each invocation, e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a),
760 // f(x, b), f(x, c)
761 #define CATCH_REC_LIST_UD(f, userdata, ...)                                                        \
762     CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
763
764 #define CATCH_REC_LIST(f, ...)                                                                     \
765     CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
766
767 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
768 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__
769 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
770 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
771 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
772 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
773 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
774 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param)                                             \
775     INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
776 #else
777 // MSVC is adding extra space and needs another indirection to expand
778 // INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
779 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
780 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
781 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param)                                             \
782     (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
783 #endif
784
785 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
786 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
787
788 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
789
790 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
791 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...)                                                        \
792     decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
793 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...)                                                         \
794     INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
795 #else
796 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...)                                                        \
797     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
798         decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
799 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...)                                                         \
800     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
801         INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
802 #endif
803
804 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)                                             \
805     CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__)
806
807 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
808 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1)                                                 \
809     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
810 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2)                                             \
811     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
812 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3)                                         \
813     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
814 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4)                                     \
815     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
816 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5)                                 \
817     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
818 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6)                             \
819     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
820 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7)                         \
821     INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
822 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8)                     \
823     INTERNAL_CATCH_REMOVE_PARENS(_0),                                                              \
824         INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
825 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9)                \
826     INTERNAL_CATCH_REMOVE_PARENS(_0),                                                              \
827         INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
828 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10)           \
829     INTERNAL_CATCH_REMOVE_PARENS(_0),                                                              \
830         INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
831
832 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
833
834 #define INTERNAL_CATCH_TYPE_GEN                                                                    \
835     template <typename...> struct TypeList {};                                                     \
836     template <typename... Ts> constexpr auto get_wrapper() noexcept->TypeList<Ts...> {             \
837         return {};                                                                                 \
838     }                                                                                              \
839     template <template <typename...> class...> struct TemplateTypeList {};                         \
840     template <template <typename...> class... Cs>                                                  \
841     constexpr auto get_wrapper() noexcept->TemplateTypeList<Cs...> {                               \
842         return {};                                                                                 \
843     }                                                                                              \
844     template <typename...> struct append;                                                          \
845     template <typename...> struct rewrap;                                                          \
846     template <template <typename...> class, typename...> struct create;                            \
847     template <template <typename...> class, typename> struct convert;                              \
848                                                                                                    \
849     template <typename T> struct append<T> { using type = T; };                                    \
850     template <template <typename...> class L1,                                                     \
851               typename... E1,                                                                      \
852               template <typename...>                                                               \
853               class L2,                                                                            \
854               typename... E2,                                                                      \
855               typename... Rest>                                                                    \
856     struct append<L1<E1...>, L2<E2...>, Rest...> {                                                 \
857         using type = typename append<L1<E1..., E2...>, Rest...>::type;                             \
858     };                                                                                             \
859     template <template <typename...> class L1, typename... E1, typename... Rest>                   \
860     struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> {                                        \
861         using type = L1<E1...>;                                                                    \
862     };                                                                                             \
863                                                                                                    \
864     template <template <typename...> class Container,                                              \
865               template <typename...>                                                               \
866               class List,                                                                          \
867               typename... elems>                                                                   \
868     struct rewrap<TemplateTypeList<Container>, List<elems...>> {                                   \
869         using type = TypeList<Container<elems...>>;                                                \
870     };                                                                                             \
871     template <template <typename...> class Container,                                              \
872               template <typename...>                                                               \
873               class List,                                                                          \
874               class... Elems,                                                                      \
875               typename... Elements>                                                                \
876     struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> {                      \
877         using type = typename append<                                                              \
878             TypeList<Container<Elems...>>,                                                         \
879             typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type;                \
880     };                                                                                             \
881                                                                                                    \
882     template <template <typename...> class Final,                                                  \
883               template <typename...>                                                               \
884               class... Containers,                                                                 \
885               typename... Types>                                                                   \
886     struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> {                    \
887         using type = typename append<                                                              \
888             Final<>,                                                                               \
889             typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type;               \
890     };                                                                                             \
891     template <template <typename...> class Final,                                                  \
892               template <typename...>                                                               \
893               class List,                                                                          \
894               typename... Ts>                                                                      \
895     struct convert<Final, List<Ts...>> {                                                           \
896         using type = typename append<Final<>, TypeList<Ts>...>::type;                              \
897     };
898
899 #define INTERNAL_CATCH_NTTP_1(signature, ...)                                                      \
900     template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp {};                             \
901     template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
902     constexpr auto get_wrapper() noexcept->Nttp<__VA_ARGS__> {                                     \
903         return {};                                                                                 \
904     }                                                                                              \
905     template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...>                         \
906     struct NttpTemplateTypeList {};                                                                \
907     template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs>                      \
908     constexpr auto get_wrapper() noexcept->NttpTemplateTypeList<Cs...> {                           \
909         return {};                                                                                 \
910     }                                                                                              \
911                                                                                                    \
912     template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container,                  \
913               template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                   \
914               class List,                                                                          \
915               INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
916     struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> {                            \
917         using type = TypeList<Container<__VA_ARGS__>>;                                             \
918     };                                                                                             \
919     template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container,                  \
920               template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                   \
921               class List,                                                                          \
922               INTERNAL_CATCH_REMOVE_PARENS(signature),                                             \
923               typename... Elements>                                                                \
924     struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> {               \
925         using type = typename append<                                                              \
926             TypeList<Container<__VA_ARGS__>>,                                                      \
927             typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type;            \
928     };                                                                                             \
929     template <template <typename...> class Final,                                                  \
930               template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                   \
931               class... Containers,                                                                 \
932               typename... Types>                                                                   \
933     struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> {                \
934         using type = typename append<                                                              \
935             Final<>,                                                                               \
936             typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type;           \
937     };
938
939 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
940 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)                                      \
941     template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
942 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)                                \
943     template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
944
945 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
946 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)                                       \
947     template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
948 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...)                                 \
949     template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
950
951 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)                                         \
952     template <typename Type> void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) {       \
953         Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>),                                    \
954                        CATCH_INTERNAL_LINEINFO,                                                    \
955                        Catch::StringRef(),                                                         \
956                        nameAndTags);                                                               \
957     }
958
959 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)                                     \
960     template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
961     void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) {                             \
962         Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>),                             \
963                        CATCH_INTERNAL_LINEINFO,                                                    \
964                        Catch::StringRef(),                                                         \
965                        nameAndTags);                                                               \
966     }
967
968 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)                             \
969     template <typename Type>                                                                       \
970     void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags) {    \
971         Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test),                              \
972                        CATCH_INTERNAL_LINEINFO,                                                    \
973                        className,                                                                  \
974                        nameAndTags);                                                               \
975     }
976
977 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)                              \
978     template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
979     void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
980         Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test),                       \
981                        CATCH_INTERNAL_LINEINFO,                                                    \
982                        className,                                                                  \
983                        nameAndTags);                                                               \
984     }
985
986 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
987 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)                    \
988     template <typename TestType>                                                                   \
989     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> {                          \
990         void test();                                                                               \
991     }
992
993 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)              \
994     template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
995     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> {                       \
996         void test();                                                                               \
997     }
998
999 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
1000 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)                                \
1001     template <typename TestType>                                                                   \
1002     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
1003 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)                          \
1004     template <INTERNAL_CATCH_REMOVE_PARENS(signature)>                                             \
1005     void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
1006
1007 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1008 #define INTERNAL_CATCH_NTTP_0
1009 #define INTERNAL_CATCH_NTTP_GEN(...)                                                               \
1010     INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__,                                                      \
1011                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1012                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1013                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1014                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1015                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1016                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1017                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1018                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1019                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1020                                  INTERNAL_CATCH_NTTP_1(__VA_ARGS__),                               \
1021                                  INTERNAL_CATCH_NTTP_0)
1022 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...)                                       \
1023     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1024                                  __VA_ARGS__,                                                      \
1025                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1026                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1027                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1028                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1029                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1030                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1031                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1032                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1033                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                          \
1034                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1,                           \
1035                                  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)                           \
1036     (TestName, __VA_ARGS__)
1037 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...)                           \
1038     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1039                                  __VA_ARGS__,                                                      \
1040                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1041                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1042                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1043                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1044                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1045                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1046                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1047                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1048                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                         \
1049                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1,                          \
1050                                  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)                          \
1051     (TestName, ClassName, __VA_ARGS__)
1052 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...)                                          \
1053     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1054                                  __VA_ARGS__,                                                      \
1055                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1056                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1057                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1058                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1059                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1060                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1061                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1062                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1063                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD,                              \
1064                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD0,                             \
1065                                  INTERNAL_CATCH_NTTP_REGISTER_METHOD0)                             \
1066     (TestName, __VA_ARGS__)
1067 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...)                                                 \
1068     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1069                                  __VA_ARGS__,                                                      \
1070                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1071                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1072                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1073                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1074                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1075                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1076                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1077                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1078                                  INTERNAL_CATCH_NTTP_REGISTER,                                     \
1079                                  INTERNAL_CATCH_NTTP_REGISTER0,                                    \
1080                                  INTERNAL_CATCH_NTTP_REGISTER0)                                    \
1081     (TestFunc, __VA_ARGS__)
1082 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...)                                              \
1083     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1084                                  __VA_ARGS__,                                                      \
1085                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1086                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1087                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1088                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1089                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1090                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1091                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1092                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1093                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1094                                  INTERNAL_CATCH_DEFINE_SIG_TEST1,                                  \
1095                                  INTERNAL_CATCH_DEFINE_SIG_TEST0)                                  \
1096     (TestName, __VA_ARGS__)
1097 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...)                                             \
1098     INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                          \
1099                                  __VA_ARGS__,                                                      \
1100                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1101                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1102                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1103                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1104                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1105                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1106                                  INTERNAL_CATCH_DEFINE_SIG_TEST_X,                                 \
1107                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1108                                  INTERNAL_CATCH_DECLARE_SIG_TEST_X,                                \
1109                                  INTERNAL_CATCH_DECLARE_SIG_TEST1,                                 \
1110                                  INTERNAL_CATCH_DECLARE_SIG_TEST0)                                 \
1111     (TestName, __VA_ARGS__)
1112 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...)                                                      \
1113     INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__,                                                      \
1114                                  INTERNAL_CATCH_REMOVE_PARENS_11_ARG,                              \
1115                                  INTERNAL_CATCH_REMOVE_PARENS_10_ARG,                              \
1116                                  INTERNAL_CATCH_REMOVE_PARENS_9_ARG,                               \
1117                                  INTERNAL_CATCH_REMOVE_PARENS_8_ARG,                               \
1118                                  INTERNAL_CATCH_REMOVE_PARENS_7_ARG,                               \
1119                                  INTERNAL_CATCH_REMOVE_PARENS_6_ARG,                               \
1120                                  INTERNAL_CATCH_REMOVE_PARENS_5_ARG,                               \
1121                                  INTERNAL_CATCH_REMOVE_PARENS_4_ARG,                               \
1122                                  INTERNAL_CATCH_REMOVE_PARENS_3_ARG,                               \
1123                                  INTERNAL_CATCH_REMOVE_PARENS_2_ARG,                               \
1124                                  INTERNAL_CATCH_REMOVE_PARENS_1_ARG)                               \
1125     (__VA_ARGS__)
1126 #else
1127 #define INTERNAL_CATCH_NTTP_0(signature)
1128 #define INTERNAL_CATCH_NTTP_GEN(...)                                                               \
1129     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__,                          \
1130                                                              INTERNAL_CATCH_NTTP_1,                \
1131                                                              INTERNAL_CATCH_NTTP_1,                \
1132                                                              INTERNAL_CATCH_NTTP_1,                \
1133                                                              INTERNAL_CATCH_NTTP_1,                \
1134                                                              INTERNAL_CATCH_NTTP_1,                \
1135                                                              INTERNAL_CATCH_NTTP_1,                \
1136                                                              INTERNAL_CATCH_NTTP_1,                \
1137                                                              INTERNAL_CATCH_NTTP_1,                \
1138                                                              INTERNAL_CATCH_NTTP_1,                \
1139                                                              INTERNAL_CATCH_NTTP_1,                \
1140                                                              INTERNAL_CATCH_NTTP_0)(__VA_ARGS__))
1141 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...)                                       \
1142     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(                                      \
1143         "dummy",                                                                                   \
1144         __VA_ARGS__,                                                                               \
1145         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1146         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1147         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1148         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1149         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1150         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1151         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1152         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1153         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,                                                   \
1154         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1,                                                    \
1155         INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
1156 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...)                           \
1157     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(                                      \
1158         "dummy",                                                                                   \
1159         __VA_ARGS__,                                                                               \
1160         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1161         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1162         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1163         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1164         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1165         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1166         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1167         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1168         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,                                                  \
1169         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1,                                                   \
1170         INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
1171 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...)                                          \
1172     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
1173         INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                      \
1174                                      __VA_ARGS__,                                                  \
1175                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1176                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1177                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1178                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1179                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1180                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1181                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1182                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1183                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD,                          \
1184                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD0,                         \
1185                                      INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
1186 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...)                                                 \
1187     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
1188         INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                      \
1189                                      __VA_ARGS__,                                                  \
1190                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1191                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1192                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1193                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1194                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1195                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1196                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1197                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1198                                      INTERNAL_CATCH_NTTP_REGISTER,                                 \
1199                                      INTERNAL_CATCH_NTTP_REGISTER0,                                \
1200                                      INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
1201 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...)                                              \
1202     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
1203         INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                      \
1204                                      __VA_ARGS__,                                                  \
1205                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1206                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1207                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1208                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1209                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1210                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1211                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1212                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1213                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1214                                      INTERNAL_CATCH_DEFINE_SIG_TEST1,                              \
1215                                      INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
1216 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...)                                             \
1217     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
1218         INTERNAL_CATCH_VA_NARGS_IMPL("dummy",                                                      \
1219                                      __VA_ARGS__,                                                  \
1220                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1221                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1222                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1223                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1224                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1225                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1226                                      INTERNAL_CATCH_DEFINE_SIG_TEST_X,                             \
1227                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1228                                      INTERNAL_CATCH_DECLARE_SIG_TEST_X,                            \
1229                                      INTERNAL_CATCH_DECLARE_SIG_TEST1,                             \
1230                                      INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
1231 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...)                                                      \
1232     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
1233         INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__,                                                  \
1234                                      INTERNAL_CATCH_REMOVE_PARENS_11_ARG,                          \
1235                                      INTERNAL_CATCH_REMOVE_PARENS_10_ARG,                          \
1236                                      INTERNAL_CATCH_REMOVE_PARENS_9_ARG,                           \
1237                                      INTERNAL_CATCH_REMOVE_PARENS_8_ARG,                           \
1238                                      INTERNAL_CATCH_REMOVE_PARENS_7_ARG,                           \
1239                                      INTERNAL_CATCH_REMOVE_PARENS_6_ARG,                           \
1240                                      INTERNAL_CATCH_REMOVE_PARENS_5_ARG,                           \
1241                                      INTERNAL_CATCH_REMOVE_PARENS_4_ARG,                           \
1242                                      INTERNAL_CATCH_REMOVE_PARENS_3_ARG,                           \
1243                                      INTERNAL_CATCH_REMOVE_PARENS_2_ARG,                           \
1244                                      INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
1245 #endif
1246
1247 // end catch_preprocessor.hpp
1248 // start catch_meta.hpp
1249
1250 #include <type_traits>
1251
1252 namespace Catch {
1253     template <typename T> struct always_false : std::false_type {};
1254
1255     template <typename> struct true_given : std::true_type {};
1256     struct is_callable_tester {
1257         template <typename Fun, typename... Args>
1258         true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
1259         template <typename...> std::false_type static test(...);
1260     };
1261
1262     template <typename T> struct is_callable;
1263
1264     template <typename Fun, typename... Args>
1265     struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
1266
1267 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1268     // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
1269     // replaced with std::invoke_result here.
1270     template <typename Func, typename... U>
1271     using FunctionReturnType =
1272         std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1273 #else
1274     // Keep ::type here because we still support C++11
1275     template <typename Func, typename... U>
1276     using FunctionReturnType = typename std::remove_reference<
1277         typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
1278 #endif
1279
1280 } // namespace Catch
1281
1282 namespace mpl_ {
1283     struct na;
1284 }
1285
1286 // end catch_meta.hpp
1287 namespace Catch {
1288
1289     template <typename C> class TestInvokerAsMethod : public ITestInvoker {
1290         void (C::*m_testAsMethod)();
1291
1292     public:
1293         TestInvokerAsMethod(void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod) {}
1294
1295         void invoke() const override {
1296             C obj;
1297             (obj.*m_testAsMethod)();
1298         }
1299     };
1300
1301     auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker*;
1302
1303     template <typename C>
1304     auto makeTestInvoker(void (C::*testAsMethod)()) noexcept -> ITestInvoker* {
1305         return new (std::nothrow) TestInvokerAsMethod<C>(testAsMethod);
1306     }
1307
1308     struct NameAndTags {
1309         NameAndTags(StringRef const& name_ = StringRef(),
1310                     StringRef const& tags_ = StringRef()) noexcept;
1311         StringRef name;
1312         StringRef tags;
1313     };
1314
1315     struct AutoReg : NonCopyable {
1316         AutoReg(ITestInvoker* invoker,
1317                 SourceLineInfo const& lineInfo,
1318                 StringRef const& classOrMethod,
1319                 NameAndTags const& nameAndTags) noexcept;
1320         ~AutoReg();
1321     };
1322
1323 } // end namespace Catch
1324
1325 #if defined(CATCH_CONFIG_DISABLE)
1326 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) static void TestName()
1327 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(TestName, ClassName, ...)                   \
1328     namespace {                                                                                    \
1329         struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) {                                \
1330             void test();                                                                           \
1331         };                                                                                         \
1332     }                                                                                              \
1333     void TestName::test()
1334 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(                                       \
1335     TestName, TestFunc, Name, Tags, Signature, ...)                                                \
1336     INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1337 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2(                                \
1338     TestNameClass, TestName, ClassName, Name, Tags, Signature, ...)                                \
1339     namespace {                                                                                    \
1340         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1341             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(                                                \
1342                 TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));                     \
1343         }                                                                                          \
1344     }                                                                                              \
1345     INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1346
1347 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1348 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...)                         \
1349     INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(                                           \
1350         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1351         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____),    \
1352         Name,                                                                                      \
1353         Tags,                                                                                      \
1354         typename TestType,                                                                         \
1355         __VA_ARGS__)
1356 #else
1357 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...)                         \
1358     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(               \
1359         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1360         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____),    \
1361         Name,                                                                                      \
1362         Tags,                                                                                      \
1363         typename TestType,                                                                         \
1364         __VA_ARGS__))
1365 #endif
1366
1367 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1368 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...)          \
1369     INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(                                           \
1370         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1371         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____),    \
1372         Name,                                                                                      \
1373         Tags,                                                                                      \
1374         Signature,                                                                                 \
1375         __VA_ARGS__)
1376 #else
1377 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...)          \
1378     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(               \
1379         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1380         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____),    \
1381         Name,                                                                                      \
1382         Tags,                                                                                      \
1383         Signature,                                                                                 \
1384         __VA_ARGS__))
1385 #endif
1386
1387 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1388 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...)       \
1389     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2(                                    \
1390         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____),  \
1391         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1392         ClassName,                                                                                 \
1393         Name,                                                                                      \
1394         Tags,                                                                                      \
1395         typename T,                                                                                \
1396         __VA_ARGS__)
1397 #else
1398 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...)       \
1399     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2(        \
1400         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____),  \
1401         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1402         ClassName,                                                                                 \
1403         Name,                                                                                      \
1404         Tags,                                                                                      \
1405         typename T,                                                                                \
1406         __VA_ARGS__))
1407 #endif
1408
1409 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1410 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(                              \
1411     ClassName, Name, Tags, Signature, ...)                                                         \
1412     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2(                                    \
1413         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____),  \
1414         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1415         ClassName,                                                                                 \
1416         Name,                                                                                      \
1417         Tags,                                                                                      \
1418         Signature,                                                                                 \
1419         __VA_ARGS__)
1420 #else
1421 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(                              \
1422     ClassName, Name, Tags, Signature, ...)                                                         \
1423     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2(        \
1424         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____),  \
1425         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1426         ClassName,                                                                                 \
1427         Name,                                                                                      \
1428         Tags,                                                                                      \
1429         Signature,                                                                                 \
1430         __VA_ARGS__))
1431 #endif
1432 #endif
1433
1434 ///////////////////////////////////////////////////////////////////////////////
1435 #define INTERNAL_CATCH_TESTCASE2(TestName, ...)                                                    \
1436     static void TestName();                                                                        \
1437     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1438     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1439     namespace {                                                                                    \
1440         Catch::AutoReg                                                                             \
1441             INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName),           \
1442                                                       CATCH_INTERNAL_LINEINFO,                     \
1443                                                       Catch::StringRef(),                          \
1444                                                       Catch::NameAndTags{__VA_ARGS__});            \
1445     } /* NOLINT */                                                                                 \
1446     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1447     static void TestName()
1448 #define INTERNAL_CATCH_TESTCASE(...)                                                               \
1449     INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), __VA_ARGS__)
1450
1451 ///////////////////////////////////////////////////////////////////////////////
1452 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...)                                   \
1453     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1454     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1455     namespace {                                                                                    \
1456         Catch::AutoReg                                                                             \
1457             INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&QualifiedMethod),    \
1458                                                       CATCH_INTERNAL_LINEINFO,                     \
1459                                                       "&" #QualifiedMethod,                        \
1460                                                       Catch::NameAndTags{__VA_ARGS__});            \
1461     } /* NOLINT */                                                                                 \
1462     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1463
1464 ///////////////////////////////////////////////////////////////////////////////
1465 #define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...)                                 \
1466     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1467     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1468     namespace {                                                                                    \
1469         struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) {                                \
1470             void test();                                                                           \
1471         };                                                                                         \
1472         Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(                                  \
1473             Catch::makeTestInvoker(&TestName::test),                                               \
1474             CATCH_INTERNAL_LINEINFO,                                                               \
1475             #ClassName,                                                                            \
1476             Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */                                         \
1477     }                                                                                              \
1478     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1479     void TestName::test()
1480 #define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...)                                            \
1481     INTERNAL_CATCH_TEST_CASE_METHOD2(                                                              \
1482         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), ClassName, __VA_ARGS__)
1483
1484 ///////////////////////////////////////////////////////////////////////////////
1485 #define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...)                                            \
1486     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1487     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1488     Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(                                      \
1489         Catch::makeTestInvoker(Function),                                                          \
1490         CATCH_INTERNAL_LINEINFO,                                                                   \
1491         Catch::StringRef(),                                                                        \
1492         Catch::NameAndTags{__VA_ARGS__}); /* NOLINT */                                             \
1493     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1494
1495 ///////////////////////////////////////////////////////////////////////////////
1496 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...)        \
1497     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1498     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1499     CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                                                 \
1500     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1501     INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));            \
1502     namespace {                                                                                    \
1503         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1504             INTERNAL_CATCH_TYPE_GEN                                                                \
1505             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))                       \
1506             INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))         \
1507             template <typename... Types> struct TestName {                                         \
1508                 TestName() {                                                                       \
1509                     int index = 0;                                                                 \
1510                     constexpr char const* tmpl_types[] = {                                         \
1511                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};     \
1512                     using expander = int[];                                                        \
1513                     (void)expander{                                                                \
1514                         (reg_test(Types{},                                                         \
1515                                   Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]),  \
1516                                                      Tags}),                                       \
1517                          index++)...}; /* NOLINT */                                                \
1518                 }                                                                                  \
1519             };                                                                                     \
1520             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1521                 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();                \
1522                 return 0;                                                                          \
1523             }();                                                                                   \
1524         }                                                                                          \
1525     }                                                                                              \
1526     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1527     INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1528
1529 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1530 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...)                                         \
1531     INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(                                                           \
1532         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1533         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____),    \
1534         Name,                                                                                      \
1535         Tags,                                                                                      \
1536         typename TestType,                                                                         \
1537         __VA_ARGS__)
1538 #else
1539 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...)                                         \
1540     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(                               \
1541         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1542         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____),    \
1543         Name,                                                                                      \
1544         Tags,                                                                                      \
1545         typename TestType,                                                                         \
1546         __VA_ARGS__))
1547 #endif
1548
1549 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1550 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...)                          \
1551     INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(                                                           \
1552         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1553         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____),    \
1554         Name,                                                                                      \
1555         Tags,                                                                                      \
1556         Signature,                                                                                 \
1557         __VA_ARGS__)
1558 #else
1559 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...)                          \
1560     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(                               \
1561         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1562         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____),    \
1563         Name,                                                                                      \
1564         Tags,                                                                                      \
1565         Signature,                                                                                 \
1566         __VA_ARGS__))
1567 #endif
1568
1569 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(                                                \
1570     TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList)                           \
1571     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1572     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1573     CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                                                 \
1574     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1575     template <typename TestType> static void TestFuncName();                                       \
1576     namespace {                                                                                    \
1577         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1578             INTERNAL_CATCH_TYPE_GEN                                                                \
1579             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))                       \
1580             template <typename... Types> struct TestName {                                         \
1581                 void reg_tests() {                                                                 \
1582                     int index = 0;                                                                 \
1583                     using expander = int[];                                                        \
1584                     constexpr char const* tmpl_types[] = {                                         \
1585                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS,                    \
1586                                        INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};                  \
1587                     constexpr char const* types_list[] = {                                         \
1588                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS,                    \
1589                                        INTERNAL_CATCH_REMOVE_PARENS(TypesList))};                  \
1590                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);         \
1591                     (void)expander{                                                                \
1592                         (Catch::AutoReg(Catch::makeTestInvoker(&TestFuncName<Types>),              \
1593                                         CATCH_INTERNAL_LINEINFO,                                   \
1594                                         Catch::StringRef(),                                        \
1595                                         Catch::NameAndTags{                                        \
1596                                             Name " - " +                                           \
1597                                                 std::string(tmpl_types[index / num_types]) + "<" + \
1598                                                 std::string(types_list[index % num_types]) + ">",  \
1599                                             Tags}),                                                \
1600                          index++)...}; /* NOLINT */                                                \
1601                 }                                                                                  \
1602             };                                                                                     \
1603             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1604                 using TestInit = typename create<                                                  \
1605                     TestName,                                                                      \
1606                     decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()),              \
1607                     TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(                            \
1608                         INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;                          \
1609                 TestInit t;                                                                        \
1610                 t.reg_tests();                                                                     \
1611                 return 0;                                                                          \
1612             }();                                                                                   \
1613         }                                                                                          \
1614     }                                                                                              \
1615     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1616     template <typename TestType> static void TestFuncName()
1617
1618 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1619 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)                                 \
1620     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(                                                    \
1621         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1622         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____),    \
1623         Name,                                                                                      \
1624         Tags,                                                                                      \
1625         typename T,                                                                                \
1626         __VA_ARGS__)
1627 #else
1628 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)                                 \
1629     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(                        \
1630         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1631         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____),    \
1632         Name,                                                                                      \
1633         Tags,                                                                                      \
1634         typename T,                                                                                \
1635         __VA_ARGS__))
1636 #endif
1637
1638 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1639 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)                  \
1640     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(                                                    \
1641         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1642         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____),    \
1643         Name,                                                                                      \
1644         Tags,                                                                                      \
1645         Signature,                                                                                 \
1646         __VA_ARGS__)
1647 #else
1648 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)                  \
1649     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(                        \
1650         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1651         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____),    \
1652         Name,                                                                                      \
1653         Tags,                                                                                      \
1654         Signature,                                                                                 \
1655         __VA_ARGS__))
1656 #endif
1657
1658 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)         \
1659     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1660     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1661     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1662     template <typename TestType> static void TestFunc();                                           \
1663     namespace {                                                                                    \
1664         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1665             INTERNAL_CATCH_TYPE_GEN                                                                \
1666             template <typename... Types> struct TestName {                                         \
1667                 void reg_tests() {                                                                 \
1668                     int index = 0;                                                                 \
1669                     using expander = int[];                                                        \
1670                     (void)expander{                                                                \
1671                         (Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Types>),                  \
1672                                         CATCH_INTERNAL_LINEINFO,                                   \
1673                                         Catch::StringRef(),                                        \
1674                                         Catch::NameAndTags{                                        \
1675                                             Name " - " +                                           \
1676                                                 std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) +  \
1677                                                 " - " + std::to_string(index),                     \
1678                                             Tags}),                                                \
1679                          index++)...}; /* NOLINT */                                                \
1680                 }                                                                                  \
1681             };                                                                                     \
1682             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1683                 using TestInit = typename convert<TestName, TmplList>::type;                       \
1684                 TestInit t;                                                                        \
1685                 t.reg_tests();                                                                     \
1686                 return 0;                                                                          \
1687             }();                                                                                   \
1688         }                                                                                          \
1689     }                                                                                              \
1690     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1691     template <typename TestType> static void TestFunc()
1692
1693 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList)                               \
1694     INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(                                                      \
1695         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1696         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____),    \
1697         Name,                                                                                      \
1698         Tags,                                                                                      \
1699         TmplList)
1700
1701 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(                                                \
1702     TestNameClass, TestName, ClassName, Name, Tags, Signature, ...)                                \
1703     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1704     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1705     CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                                                 \
1706     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1707     namespace {                                                                                    \
1708         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1709             INTERNAL_CATCH_TYPE_GEN                                                                \
1710             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))                       \
1711             INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(                                                \
1712                 TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));                     \
1713             INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))  \
1714             template <typename... Types> struct TestNameClass {                                    \
1715                 TestNameClass() {                                                                  \
1716                     int index = 0;                                                                 \
1717                     constexpr char const* tmpl_types[] = {                                         \
1718                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};     \
1719                     using expander = int[];                                                        \
1720                     (void)expander{                                                                \
1721                         (reg_test(Types{},                                                         \
1722                                   #ClassName,                                                      \
1723                                   Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]),  \
1724                                                      Tags}),                                       \
1725                          index++)...}; /* NOLINT */                                                \
1726                 }                                                                                  \
1727             };                                                                                     \
1728             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1729                 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();           \
1730                 return 0;                                                                          \
1731             }();                                                                                   \
1732         }                                                                                          \
1733     }                                                                                              \
1734     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1735     INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1736
1737 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1738 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...)                       \
1739     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(                                                    \
1740         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____),  \
1741         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1742         ClassName,                                                                                 \
1743         Name,                                                                                      \
1744         Tags,                                                                                      \
1745         typename T,                                                                                \
1746         __VA_ARGS__)
1747 #else
1748 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...)                       \
1749     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(                        \
1750         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____),  \
1751         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1752         ClassName,                                                                                 \
1753         Name,                                                                                      \
1754         Tags,                                                                                      \
1755         typename T,                                                                                \
1756         __VA_ARGS__))
1757 #endif
1758
1759 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1760 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...)        \
1761     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(                                                    \
1762         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____),  \
1763         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1764         ClassName,                                                                                 \
1765         Name,                                                                                      \
1766         Tags,                                                                                      \
1767         Signature,                                                                                 \
1768         __VA_ARGS__)
1769 #else
1770 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...)        \
1771     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(                        \
1772         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____),  \
1773         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1774         ClassName,                                                                                 \
1775         Name,                                                                                      \
1776         Tags,                                                                                      \
1777         Signature,                                                                                 \
1778         __VA_ARGS__))
1779 #endif
1780
1781 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(                                        \
1782     TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)               \
1783     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1784     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1785     CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS                                                 \
1786     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1787     template <typename TestType>                                                                   \
1788     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) {                          \
1789         void test();                                                                               \
1790     };                                                                                             \
1791     namespace {                                                                                    \
1792         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {                                   \
1793             INTERNAL_CATCH_TYPE_GEN                                                                \
1794             INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))                       \
1795             template <typename... Types> struct TestNameClass {                                    \
1796                 void reg_tests() {                                                                 \
1797                     int index = 0;                                                                 \
1798                     using expander = int[];                                                        \
1799                     constexpr char const* tmpl_types[] = {                                         \
1800                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS,                    \
1801                                        INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};                  \
1802                     constexpr char const* types_list[] = {                                         \
1803                         CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS,                    \
1804                                        INTERNAL_CATCH_REMOVE_PARENS(TypesList))};                  \
1805                     constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);         \
1806                     (void)expander{                                                                \
1807                         (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test),            \
1808                                         CATCH_INTERNAL_LINEINFO,                                   \
1809                                         #ClassName,                                                \
1810                                         Catch::NameAndTags{                                        \
1811                                             Name " - " +                                           \
1812                                                 std::string(tmpl_types[index / num_types]) + "<" + \
1813                                                 std::string(types_list[index % num_types]) + ">",  \
1814                                             Tags}),                                                \
1815                          index++)...}; /* NOLINT */                                                \
1816                 }                                                                                  \
1817             };                                                                                     \
1818             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1819                 using TestInit = typename create<                                                  \
1820                     TestNameClass,                                                                 \
1821                     decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()),              \
1822                     TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(                            \
1823                         INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;                          \
1824                 TestInit t;                                                                        \
1825                 t.reg_tests();                                                                     \
1826                 return 0;                                                                          \
1827             }();                                                                                   \
1828         }                                                                                          \
1829     }                                                                                              \
1830     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1831     template <typename TestType> void TestName<TestType>::test()
1832
1833 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1834 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...)               \
1835     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(                                            \
1836         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1837         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____),    \
1838         ClassName,                                                                                 \
1839         Name,                                                                                      \
1840         Tags,                                                                                      \
1841         typename T,                                                                                \
1842         __VA_ARGS__)
1843 #else
1844 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...)               \
1845     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(                \
1846         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1847         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____),    \
1848         ClassName,                                                                                 \
1849         Name,                                                                                      \
1850         Tags,                                                                                      \
1851         typename T,                                                                                \
1852         __VA_ARGS__))
1853 #endif
1854
1855 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1856 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(                                      \
1857     ClassName, Name, Tags, Signature, ...)                                                         \
1858     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(                                            \
1859         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1860         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____),    \
1861         ClassName,                                                                                 \
1862         Name,                                                                                      \
1863         Tags,                                                                                      \
1864         Signature,                                                                                 \
1865         __VA_ARGS__)
1866 #else
1867 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(                                      \
1868     ClassName, Name, Tags, Signature, ...)                                                         \
1869     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(                \
1870         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1871         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____),    \
1872         ClassName,                                                                                 \
1873         Name,                                                                                      \
1874         Tags,                                                                                      \
1875         Signature,                                                                                 \
1876         __VA_ARGS__))
1877 #endif
1878
1879 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(                                           \
1880     TestNameClass, TestName, ClassName, Name, Tags, TmplList)                                      \
1881     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
1882     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
1883     CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS                                               \
1884     template <typename TestType>                                                                   \
1885     struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) {                          \
1886         void test();                                                                               \
1887     };                                                                                             \
1888     namespace {                                                                                    \
1889         namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) {                                        \
1890             INTERNAL_CATCH_TYPE_GEN                                                                \
1891             template <typename... Types> struct TestNameClass {                                    \
1892                 void reg_tests() {                                                                 \
1893                     int index = 0;                                                                 \
1894                     using expander = int[];                                                        \
1895                     (void)expander{                                                                \
1896                         (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test),            \
1897                                         CATCH_INTERNAL_LINEINFO,                                   \
1898                                         #ClassName,                                                \
1899                                         Catch::NameAndTags{                                        \
1900                                             Name " - " +                                           \
1901                                                 std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) +  \
1902                                                 " - " + std::to_string(index),                     \
1903                                             Tags}),                                                \
1904                          index++)...}; /* NOLINT */                                                \
1905                 }                                                                                  \
1906             };                                                                                     \
1907             static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() {                        \
1908                 using TestInit = typename convert<TestNameClass, TmplList>::type;                  \
1909                 TestInit t;                                                                        \
1910                 t.reg_tests();                                                                     \
1911                 return 0;                                                                          \
1912             }();                                                                                   \
1913         }                                                                                          \
1914     }                                                                                              \
1915     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
1916     template <typename TestType> void TestName<TestType>::test()
1917
1918 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList)             \
1919     INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(                                               \
1920         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____),               \
1921         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____),    \
1922         ClassName,                                                                                 \
1923         Name,                                                                                      \
1924         Tags,                                                                                      \
1925         TmplList)
1926
1927 // end catch_test_registry.h
1928 // start catch_capture.hpp
1929
1930 // start catch_assertionhandler.h
1931
1932 // start catch_assertioninfo.h
1933
1934 // start catch_result_type.h
1935
1936 namespace Catch {
1937
1938     // ResultWas::OfType enum
1939     struct ResultWas {
1940         enum OfType {
1941             Unknown = -1,
1942             Ok = 0,
1943             Info = 1,
1944             Warning = 2,
1945
1946             FailureBit = 0x10,
1947
1948             ExpressionFailed = FailureBit | 1,
1949             ExplicitFailure = FailureBit | 2,
1950
1951             Exception = 0x100 | FailureBit,
1952
1953             ThrewException = Exception | 1,
1954             DidntThrowException = Exception | 2,
1955
1956             FatalErrorCondition = 0x200 | FailureBit
1957
1958         };
1959     };
1960
1961     bool isOk(ResultWas::OfType resultType);
1962     bool isJustInfo(int flags);
1963
1964     // ResultDisposition::Flags enum
1965     struct ResultDisposition {
1966         enum Flags {
1967             Normal = 0x01,
1968
1969             ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1970             FalseTest = 0x04,         // Prefix expression with !
1971             SuppressFail = 0x08       // Failures are reported but do not fail the test
1972         };
1973     };
1974
1975     ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
1976
1977     bool shouldContinueOnFailure(int flags);
1978     inline bool isFalseTest(int flags) { return (flags & ResultDisposition::FalseTest) != 0; }
1979     bool shouldSuppressFailure(int flags);
1980
1981 } // end namespace Catch
1982
1983 // end catch_result_type.h
1984 namespace Catch {
1985
1986     struct AssertionInfo {
1987         StringRef macroName;
1988         SourceLineInfo lineInfo;
1989         StringRef capturedExpression;
1990         ResultDisposition::Flags resultDisposition;
1991
1992         // We want to delete this constructor but a compiler bug in 4.8 means
1993         // the struct is then treated as non-aggregate
1994         // AssertionInfo() = delete;
1995     };
1996
1997 } // end namespace Catch
1998
1999 // end catch_assertioninfo.h
2000 // start catch_decomposer.h
2001
2002 // start catch_tostring.h
2003
2004 #include <vector>
2005 #include <cstddef>
2006 #include <type_traits>
2007 #include <string>
2008 // start catch_stream.h
2009
2010 #include <iosfwd>
2011 #include <cstddef>
2012 #include <ostream>
2013
2014 namespace Catch {
2015
2016     std::ostream& cout();
2017     std::ostream& cerr();
2018     std::ostream& clog();
2019
2020     class StringRef;
2021
2022     struct IStream {
2023         virtual ~IStream();
2024         virtual std::ostream& stream() const = 0;
2025     };
2026
2027     auto makeStream(StringRef const& filename) -> IStream const*;
2028
2029     class ReusableStringStream : NonCopyable {
2030         std::size_t m_index;
2031         std::ostream* m_oss;
2032
2033     public:
2034         ReusableStringStream();
2035         ~ReusableStringStream();
2036
2037         auto str() const -> std::string;
2038
2039         template <typename T> auto operator<<(T const& value) -> ReusableStringStream& {
2040             *m_oss << value;
2041             return *this;
2042         }
2043         auto get() -> std::ostream& { return *m_oss; }
2044     };
2045 } // namespace Catch
2046
2047 // end catch_stream.h
2048 // start catch_interfaces_enum_values_registry.h
2049
2050 #include <vector>
2051
2052 namespace Catch {
2053
2054     namespace Detail {
2055         struct EnumInfo {
2056             StringRef m_name;
2057             std::vector<std::pair<int, StringRef>> m_values;
2058
2059             ~EnumInfo();
2060
2061             StringRef lookup(int value) const;
2062         };
2063     } // namespace Detail
2064
2065     struct IMutableEnumValuesRegistry {
2066         virtual ~IMutableEnumValuesRegistry();
2067
2068         virtual Detail::EnumInfo const&
2069         registerEnum(StringRef enumName, StringRef allEnums, std::vector<int> const& values) = 0;
2070
2071         template <typename E>
2072         Detail::EnumInfo const&
2073         registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list<E> values) {
2074             static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
2075             std::vector<int> intValues;
2076             intValues.reserve(values.size());
2077             for (auto enumValue : values)
2078                 intValues.push_back(static_cast<int>(enumValue));
2079             return registerEnum(enumName, allEnums, intValues);
2080         }
2081     };
2082
2083 } // namespace Catch
2084
2085 // end catch_interfaces_enum_values_registry.h
2086
2087 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2088 #include <string_view>
2089 #endif
2090
2091 #ifdef __OBJC__
2092 // start catch_objc_arc.hpp
2093
2094 #import <Foundation/Foundation.h>
2095
2096 #ifdef __has_feature
2097 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
2098 #else
2099 #define CATCH_ARC_ENABLED 0
2100 #endif
2101
2102 void arcSafeRelease(NSObject* obj);
2103 id performOptionalSelector(id obj, SEL sel);
2104
2105 #if !CATCH_ARC_ENABLED
2106 inline void arcSafeRelease(NSObject* obj) { [obj release]; }
2107 inline id performOptionalSelector(id obj, SEL sel) {
2108     if ([obj respondsToSelector:sel])
2109         return [obj performSelector:sel];
2110     return nil;
2111 }
2112 #define CATCH_UNSAFE_UNRETAINED
2113 #define CATCH_ARC_STRONG
2114 #else
2115 inline void arcSafeRelease(NSObject*) {}
2116 inline id performOptionalSelector(id obj, SEL sel) {
2117 #ifdef __clang__
2118 #pragma clang diagnostic push
2119 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
2120 #endif
2121     if ([obj respondsToSelector:sel])
2122         return [obj performSelector:sel];
2123 #ifdef __clang__
2124 #pragma clang diagnostic pop
2125 #endif
2126     return nil;
2127 }
2128 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
2129 #define CATCH_ARC_STRONG __strong
2130 #endif
2131
2132 // end catch_objc_arc.hpp
2133 #endif
2134
2135 #ifdef _MSC_VER
2136 #pragma warning(push)
2137 #pragma warning(disable : 4180) // We attempt to stream a function (address) by const&,
2138                                 // which MSVC complains about but is harmless
2139 #endif
2140
2141 namespace Catch {
2142     namespace Detail {
2143
2144         extern const std::string unprintableString;
2145
2146         std::string rawMemoryToString(const void* object, std::size_t size);
2147
2148         template <typename T> std::string rawMemoryToString(const T& object) {
2149             return rawMemoryToString(&object, sizeof(object));
2150         }
2151
2152         template <typename T> class IsStreamInsertable {
2153             template <typename Stream, typename U>
2154             static auto test(int)
2155                 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
2156
2157             template <typename, typename> static auto test(...) -> std::false_type;
2158
2159         public:
2160             static const bool value = decltype(test<std::ostream, const T&>(0))::value;
2161         };
2162
2163         template <typename E> std::string convertUnknownEnumToString(E e);
2164
2165         template <typename T>
2166         typename std::enable_if<!std::is_enum<T>::value &&
2167                                     !std::is_base_of<std::exception, T>::value,
2168                                 std::string>::type
2169         convertUnstreamable(T const&) {
2170             return Detail::unprintableString;
2171         }
2172         template <typename T>
2173         typename std::enable_if<!std::is_enum<T>::value &&
2174                                     std::is_base_of<std::exception, T>::value,
2175                                 std::string>::type
2176         convertUnstreamable(T const& ex) {
2177             return ex.what();
2178         }
2179
2180         template <typename T>
2181         typename std::enable_if<std::is_enum<T>::value, std::string>::type
2182         convertUnstreamable(T const& value) {
2183             return convertUnknownEnumToString(value);
2184         }
2185
2186 #if defined(_MANAGED)
2187         //! Convert a CLR string to a utf8 std::string
2188         template <typename T> std::string clrReferenceToString(T ^ ref) {
2189             if (ref == nullptr)
2190                 return std::string("null");
2191             auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
2192             cli::pin_ptr<System::Byte> p = &bytes[0];
2193             return std::string(reinterpret_cast<char const*>(p), bytes->Length);
2194         }
2195 #endif
2196
2197     } // namespace Detail
2198
2199     // If we decide for C++14, change these to enable_if_ts
2200     template <typename T, typename = void> struct StringMaker {
2201         template <typename Fake = T>
2202         static typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value,
2203                                        std::string>::type
2204         convert(const Fake& value) {
2205             ReusableStringStream rss;
2206             // NB: call using the function-like syntax to avoid ambiguity with
2207             // user-defined templated operator<< under clang.
2208             rss.operator<<(value);
2209             return rss.str();
2210         }
2211
2212         template <typename Fake = T>
2213         static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value,
2214                                        std::string>::type
2215         convert(const Fake& value) {
2216 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
2217             return Detail::convertUnstreamable(value);
2218 #else
2219             return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
2220 #endif
2221         }
2222     };
2223
2224     namespace Detail {
2225
2226         // This function dispatches all stringification requests inside of
2227         // Catch. Should be preferably called fully qualified, like
2228         // ::Catch::Detail::stringify
2229         template <typename T> std::string stringify(const T& e) {
2230             return ::Catch::StringMaker<
2231                 typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
2232         }
2233
2234         template <typename E> std::string convertUnknownEnumToString(E e) {
2235             return ::Catch::Detail::stringify(
2236                 static_cast<typename std::underlying_type<E>::type>(e));
2237         }
2238
2239 #if defined(_MANAGED)
2240         template <typename T> std::string stringify(T ^ e) {
2241             return ::Catch::StringMaker<T ^>::convert(e);
2242         }
2243 #endif
2244
2245     } // namespace Detail
2246
2247     // Some predefined specializations
2248
2249     template <> struct StringMaker<std::string> {
2250         static std::string convert(const std::string& str);
2251     };
2252
2253 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2254     template <> struct StringMaker<std::string_view> {
2255         static std::string convert(std::string_view str);
2256     };
2257 #endif
2258
2259     template <> struct StringMaker<char const*> { static std::string convert(char const* str); };
2260     template <> struct StringMaker<char*> { static std::string convert(char* str); };
2261
2262 #ifdef CATCH_CONFIG_WCHAR
2263     template <> struct StringMaker<std::wstring> {
2264         static std::string convert(const std::wstring& wstr);
2265     };
2266
2267 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2268     template <> struct StringMaker<std::wstring_view> {
2269         static std::string convert(std::wstring_view str);
2270     };
2271 #endif
2272
2273     template <> struct StringMaker<wchar_t const*> {
2274         static std::string convert(wchar_t const* str);
2275     };
2276     template <> struct StringMaker<wchar_t*> { static std::string convert(wchar_t* str); };
2277 #endif
2278
2279     // TBD: Should we use `strnlen` to ensure that we don't go out of the
2280     // buffer,
2281     //      while keeping string semantics?
2282     template <int SZ> struct StringMaker<char[SZ]> {
2283         static std::string convert(char const* str) {
2284             return ::Catch::Detail::stringify(std::string{str});
2285         }
2286     };
2287     template <int SZ> struct StringMaker<signed char[SZ]> {
2288         static std::string convert(signed char const* str) {
2289             return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2290         }
2291     };
2292     template <int SZ> struct StringMaker<unsigned char[SZ]> {
2293         static std::string convert(unsigned char const* str) {
2294             return ::Catch::Detail::stringify(std::string{reinterpret_cast<char const*>(str)});
2295         }
2296     };
2297
2298 #if defined(CATCH_CONFIG_CPP17_BYTE)
2299     template <> struct StringMaker<std::byte> { static std::string convert(std::byte value); };
2300 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
2301     template <> struct StringMaker<int> { static std::string convert(int value); };
2302     template <> struct StringMaker<long> { static std::string convert(long value); };
2303     template <> struct StringMaker<long long> { static std::string convert(long long value); };
2304     template <> struct StringMaker<unsigned int> {
2305         static std::string convert(unsigned int value);
2306     };
2307     template <> struct StringMaker<unsigned long> {
2308         static std::string convert(unsigned long value);
2309     };
2310     template <> struct StringMaker<unsigned long long> {
2311         static std::string convert(unsigned long long value);
2312     };
2313
2314     template <> struct StringMaker<bool> { static std::string convert(bool b); };
2315
2316     template <> struct StringMaker<char> { static std::string convert(char c); };
2317     template <> struct StringMaker<signed char> { static std::string convert(signed char c); };
2318     template <> struct StringMaker<unsigned char> { static std::string convert(unsigned char c); };
2319
2320     template <> struct StringMaker<std::nullptr_t> { static std::string convert(std::nullptr_t); };
2321
2322     template <> struct StringMaker<float> {
2323         static std::string convert(float value);
2324         static int precision;
2325     };
2326
2327     template <> struct StringMaker<double> {
2328         static std::string convert(double value);
2329         static int precision;
2330     };
2331
2332     template <typename T> struct StringMaker<T*> {
2333         template <typename U> static std::string convert(U* p) {
2334             if (p) {
2335                 return ::Catch::Detail::rawMemoryToString(p);
2336             } else {
2337                 return "nullptr";
2338             }
2339         }
2340     };
2341
2342     template <typename R, typename C> struct StringMaker<R C::*> {
2343         static std::string convert(R C::*p) {
2344             if (p) {
2345                 return ::Catch::Detail::rawMemoryToString(p);
2346             } else {
2347                 return "nullptr";
2348             }
2349         }
2350     };
2351
2352 #if defined(_MANAGED)
2353     template <typename T> struct StringMaker<T ^> {
2354         static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); }
2355     };
2356 #endif
2357
2358     namespace Detail {
2359         template <typename InputIterator, typename Sentinel = InputIterator>
2360         std::string rangeToString(InputIterator first, Sentinel last) {
2361             ReusableStringStream rss;
2362             rss << "{ ";
2363             if (first != last) {
2364                 rss << ::Catch::Detail::stringify(*first);
2365                 for (++first; first != last; ++first)
2366                     rss << ", " << ::Catch::Detail::stringify(*first);
2367             }
2368             rss << " }";
2369             return rss.str();
2370         }
2371     } // namespace Detail
2372
2373 #ifdef __OBJC__
2374     template <> struct StringMaker<NSString*> {
2375         static std::string convert(NSString* nsstring) {
2376             if (!nsstring)
2377                 return "nil";
2378             return std::string("@") + [nsstring UTF8String];
2379         }
2380     };
2381     template <> struct StringMaker<NSObject*> {
2382         static std::string convert(NSObject* nsObject) {
2383             return ::Catch::Detail::stringify([nsObject description]);
2384         }
2385     };
2386     namespace Detail {
2387         inline std::string stringify(NSString* nsstring) {
2388             return StringMaker<NSString*>::convert(nsstring);
2389         }
2390
2391     }  // namespace Detail
2392 #endif // __OBJC__
2393
2394 } // namespace Catch
2395
2396 //////////////////////////////////////////////////////
2397 // Separate std-lib types stringification, so it can be selectively enabled
2398 // This means that we do not bring in
2399
2400 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
2401 #define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2402 #define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2403 #define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2404 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2405 #define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2406 #endif
2407
2408 // Separate std::pair specialization
2409 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
2410 #include <utility>
2411 namespace Catch {
2412     template <typename T1, typename T2> struct StringMaker<std::pair<T1, T2>> {
2413         static std::string convert(const std::pair<T1, T2>& pair) {
2414             ReusableStringStream rss;
2415             rss << "{ " << ::Catch::Detail::stringify(pair.first) << ", "
2416                 << ::Catch::Detail::stringify(pair.second) << " }";
2417             return rss.str();
2418         }
2419     };
2420 } // namespace Catch
2421 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2422
2423 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
2424 #include <optional>
2425 namespace Catch {
2426     template <typename T> struct StringMaker<std::optional<T>> {
2427         static std::string convert(const std::optional<T>& optional) {
2428             ReusableStringStream rss;
2429             if (optional.has_value()) {
2430                 rss << ::Catch::Detail::stringify(*optional);
2431             } else {
2432                 rss << "{ }";
2433             }
2434             return rss.str();
2435         }
2436     };
2437 } // namespace Catch
2438 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2439
2440 // Separate std::tuple specialization
2441 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
2442 #include <tuple>
2443 namespace Catch {
2444     namespace Detail {
2445         template <typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size<Tuple>::value)>
2446         struct TupleElementPrinter {
2447             static void print(const Tuple& tuple, std::ostream& os) {
2448                 os << (N ? ", " : " ") << ::Catch::Detail::stringify(std::get<N>(tuple));
2449                 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
2450             }
2451         };
2452
2453         template <typename Tuple, std::size_t N> struct TupleElementPrinter<Tuple, N, false> {
2454             static void print(const Tuple&, std::ostream&) {}
2455         };
2456
2457     } // namespace Detail
2458
2459     template <typename... Types> struct StringMaker<std::tuple<Types...>> {
2460         static std::string convert(const std::tuple<Types...>& tuple) {
2461             ReusableStringStream rss;
2462             rss << '{';
2463             Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
2464             rss << " }";
2465             return rss.str();
2466         }
2467     };
2468 } // namespace Catch
2469 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2470
2471 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
2472 #include <variant>
2473 namespace Catch {
2474     template <> struct StringMaker<std::monostate> {
2475         static std::string convert(const std::monostate&) { return "{ }"; }
2476     };
2477
2478     template <typename... Elements> struct StringMaker<std::variant<Elements...>> {
2479         static std::string convert(const std::variant<Elements...>& variant) {
2480             if (variant.valueless_by_exception()) {
2481                 return "{valueless variant}";
2482             } else {
2483                 return std::visit(
2484                     [](const auto& value) { return ::Catch::Detail::stringify(value); }, variant);
2485             }
2486         }
2487     };
2488 } // namespace Catch
2489 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2490
2491 namespace Catch {
2492     // Import begin/ end from std here
2493     using std::begin;
2494     using std::end;
2495
2496     namespace detail {
2497         template <typename...> struct void_type { using type = void; };
2498
2499         template <typename T, typename = void> struct is_range_impl : std::false_type {};
2500
2501         template <typename T>
2502         struct is_range_impl<T, typename void_type<decltype(begin(std::declval<T>()))>::type>
2503             : std::true_type {};
2504     } // namespace detail
2505
2506     template <typename T> struct is_range : detail::is_range_impl<T> {};
2507
2508 #if defined(_MANAGED) // Managed types are never ranges
2509     template <typename T> struct is_range<T ^> { static const bool value = false; };
2510 #endif
2511
2512     template <typename Range> std::string rangeToString(Range const& range) {
2513         return ::Catch::Detail::rangeToString(begin(range), end(range));
2514     }
2515
2516     // Handle vector<bool> specially
2517     template <typename Allocator> std::string rangeToString(std::vector<bool, Allocator> const& v) {
2518         ReusableStringStream rss;
2519         rss << "{ ";
2520         bool first = true;
2521         for (bool b : v) {
2522             if (first)
2523                 first = false;
2524             else
2525                 rss << ", ";
2526             rss << ::Catch::Detail::stringify(b);
2527         }
2528         rss << " }";
2529         return rss.str();
2530     }
2531
2532     template <typename R>
2533     struct StringMaker<
2534         R,
2535         typename std::enable_if<is_range<R>::value &&
2536                                 !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2537         static std::string convert(R const& range) { return rangeToString(range); }
2538     };
2539
2540     template <typename T, int SZ> struct StringMaker<T[SZ]> {
2541         static std::string convert(T const (&arr)[SZ]) { return rangeToString(arr); }
2542     };
2543
2544 } // namespace Catch
2545
2546 // Separate std::chrono::duration specialization
2547 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2548 #include <ctime>
2549 #include <ratio>
2550 #include <chrono>
2551
2552 namespace Catch {
2553
2554     template <class Ratio> struct ratio_string { static std::string symbol(); };
2555
2556     template <class Ratio> std::string ratio_string<Ratio>::symbol() {
2557         Catch::ReusableStringStream rss;
2558         rss << '[' << Ratio::num << '/' << Ratio::den << ']';
2559         return rss.str();
2560     }
2561     template <> struct ratio_string<std::atto> { static std::string symbol(); };
2562     template <> struct ratio_string<std::femto> { static std::string symbol(); };
2563     template <> struct ratio_string<std::pico> { static std::string symbol(); };
2564     template <> struct ratio_string<std::nano> { static std::string symbol(); };
2565     template <> struct ratio_string<std::micro> { static std::string symbol(); };
2566     template <> struct ratio_string<std::milli> { static std::string symbol(); };
2567
2568     ////////////
2569     // std::chrono::duration specializations
2570     template <typename Value, typename Ratio>
2571     struct StringMaker<std::chrono::duration<Value, Ratio>> {
2572         static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2573             ReusableStringStream rss;
2574             rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2575             return rss.str();
2576         }
2577     };
2578     template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2579         static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2580             ReusableStringStream rss;
2581             rss << duration.count() << " s";
2582             return rss.str();
2583         }
2584     };
2585     template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2586         static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2587             ReusableStringStream rss;
2588             rss << duration.count() << " m";
2589             return rss.str();
2590         }
2591     };
2592     template <typename Value> struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2593         static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2594             ReusableStringStream rss;
2595             rss << duration.count() << " h";
2596             return rss.str();
2597         }
2598     };
2599
2600     ////////////
2601     // std::chrono::time_point specialization
2602     // Generic time_point cannot be specialized, only
2603     // std::chrono::time_point<system_clock>
2604     template <typename Clock, typename Duration>
2605     struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2606         static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2607             return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2608         }
2609     };
2610     // std::chrono::time_point<system_clock> specialization
2611     template <typename Duration>
2612     struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2613         static std::string
2614         convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2615             auto converted = std::chrono::system_clock::to_time_t(time_point);
2616
2617 #ifdef _MSC_VER
2618             std::tm timeInfo = {};
2619             gmtime_s(&timeInfo, &converted);
2620 #else
2621             std::tm* timeInfo = std::gmtime(&converted);
2622 #endif
2623
2624             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2625             char timeStamp[timeStampSize];
2626             const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
2627
2628 #ifdef _MSC_VER
2629             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2630 #else
2631             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2632 #endif
2633             return std::string(timeStamp);
2634         }
2635     };
2636 } // namespace Catch
2637 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2638
2639 #define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...)                                                \
2640     namespace Catch {                                                                              \
2641         template <> struct StringMaker<enumName> {                                                 \
2642             static std::string convert(enumName value) {                                           \
2643                 static const auto& enumInfo =                                                      \
2644                     ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum(  \
2645                         #enumName, #__VA_ARGS__, {__VA_ARGS__});                                   \
2646                 return static_cast<std::string>(enumInfo.lookup(static_cast<int>(value)));         \
2647             }                                                                                      \
2648         };                                                                                         \
2649     }
2650
2651 #define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__)
2652
2653 #ifdef _MSC_VER
2654 #pragma warning(pop)
2655 #endif
2656
2657 // end catch_tostring.h
2658 #include <iosfwd>
2659
2660 #ifdef _MSC_VER
2661 #pragma warning(push)
2662 #pragma warning(disable : 4389) // '==' : signed/unsigned mismatch
2663 #pragma warning(disable : 4018) // more "signed/unsigned mismatch"
2664 #pragma warning(disable : 4312) // Converting int to T* using reinterpret_cast
2665                                 // (issue on x64 platform)
2666 #pragma warning(disable : 4180) // qualifier applied to function type has no meaning
2667 #pragma warning(disable : 4800) // Forcing result to true or false
2668 #endif
2669
2670 namespace Catch {
2671
2672     struct ITransientExpression {
2673         auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2674         auto getResult() const -> bool { return m_result; }
2675         virtual void streamReconstructedExpression(std::ostream& os) const = 0;
2676
2677         ITransientExpression(bool isBinaryExpression, bool result) :
2678             m_isBinaryExpression(isBinaryExpression), m_result(result) {}
2679
2680         // We don't actually need a virtual destructor, but many static
2681         // analysers complain if it's not here :-(
2682         virtual ~ITransientExpression();
2683
2684         bool m_isBinaryExpression;
2685         bool m_result;
2686     };
2687
2688     void formatReconstructedExpression(std::ostream& os,
2689                                        std::string const& lhs,
2690                                        StringRef op,
2691                                        std::string const& rhs);
2692
2693     template <typename LhsT, typename RhsT> class BinaryExpr : public ITransientExpression {
2694         LhsT m_lhs;
2695         StringRef m_op;
2696         RhsT m_rhs;
2697
2698         void streamReconstructedExpression(std::ostream& os) const override {
2699             formatReconstructedExpression(
2700                 os, Catch::Detail::stringify(m_lhs), m_op, Catch::Detail::stringify(m_rhs));
2701         }
2702
2703     public:
2704         BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs) :
2705             ITransientExpression{true, comparisonResult}, m_lhs(lhs), m_op(op), m_rhs(rhs) {}
2706
2707         template <typename T> auto operator&&(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2708             static_assert(always_false<T>::value,
2709                           "chained comparisons are not supported inside assertions, "
2710                           "wrap the expression inside parentheses, or decompose it");
2711         }
2712
2713         template <typename T> auto operator||(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2714             static_assert(always_false<T>::value,
2715                           "chained comparisons are not supported inside assertions, "
2716                           "wrap the expression inside parentheses, or decompose it");
2717         }
2718
2719         template <typename T> auto operator==(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2720             static_assert(always_false<T>::value,
2721                           "chained comparisons are not supported inside assertions, "
2722                           "wrap the expression inside parentheses, or decompose it");
2723         }
2724
2725         template <typename T> auto operator!=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2726             static_assert(always_false<T>::value,
2727                           "chained comparisons are not supported inside assertions, "
2728                           "wrap the expression inside parentheses, or decompose it");
2729         }
2730
2731         template <typename T> auto operator>(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2732             static_assert(always_false<T>::value,
2733                           "chained comparisons are not supported inside assertions, "
2734                           "wrap the expression inside parentheses, or decompose it");
2735         }
2736
2737         template <typename T> auto operator<(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2738             static_assert(always_false<T>::value,
2739                           "chained comparisons are not supported inside assertions, "
2740                           "wrap the expression inside parentheses, or decompose it");
2741         }
2742
2743         template <typename T> auto operator>=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2744             static_assert(always_false<T>::value,
2745                           "chained comparisons are not supported inside assertions, "
2746                           "wrap the expression inside parentheses, or decompose it");
2747         }
2748
2749         template <typename T> auto operator<=(T) const -> BinaryExpr<LhsT, RhsT const&> const {
2750             static_assert(always_false<T>::value,
2751                           "chained comparisons are not supported inside assertions, "
2752                           "wrap the expression inside parentheses, or decompose it");
2753         }
2754     };
2755
2756     template <typename LhsT> class UnaryExpr : public ITransientExpression {
2757         LhsT m_lhs;
2758
2759         void streamReconstructedExpression(std::ostream& os) const override {
2760             os << Catch::Detail::stringify(m_lhs);
2761         }
2762
2763     public:
2764         explicit UnaryExpr(LhsT lhs) :
2765             ITransientExpression{false, static_cast<bool>(lhs)}, m_lhs(lhs) {}
2766     };
2767
2768     // Specialised comparison functions to handle equality comparisons between
2769     // ints and pointers (NULL deduces as an int)
2770     template <typename LhsT, typename RhsT>
2771     auto compareEqual(LhsT const& lhs, RhsT const& rhs) -> bool {
2772         return static_cast<bool>(lhs == rhs);
2773     }
2774     template <typename T> auto compareEqual(T* const& lhs, int rhs) -> bool {
2775         return lhs == reinterpret_cast<void const*>(rhs);
2776     }
2777     template <typename T> auto compareEqual(T* const& lhs, long rhs) -> bool {
2778         return lhs == reinterpret_cast<void const*>(rhs);
2779     }
2780     template <typename T> auto compareEqual(int lhs, T* const& rhs) -> bool {
2781         return reinterpret_cast<void const*>(lhs) == rhs;
2782     }
2783     template <typename T> auto compareEqual(long lhs, T* const& rhs) -> bool {
2784         return reinterpret_cast<void const*>(lhs) == rhs;
2785     }
2786
2787     template <typename LhsT, typename RhsT>
2788     auto compareNotEqual(LhsT const& lhs, RhsT&& rhs) -> bool {
2789         return static_cast<bool>(lhs != rhs);
2790     }
2791     template <typename T> auto compareNotEqual(T* const& lhs, int rhs) -> bool {
2792         return lhs != reinterpret_cast<void const*>(rhs);
2793     }
2794     template <typename T> auto compareNotEqual(T* const& lhs, long rhs) -> bool {
2795         return lhs != reinterpret_cast<void const*>(rhs);
2796     }
2797     template <typename T> auto compareNotEqual(int lhs, T* const& rhs) -> bool {
2798         return reinterpret_cast<void const*>(lhs) != rhs;
2799     }
2800     template <typename T> auto compareNotEqual(long lhs, T* const& rhs) -> bool {
2801         return reinterpret_cast<void const*>(lhs) != rhs;
2802     }
2803
2804     template <typename LhsT> class ExprLhs {
2805         LhsT m_lhs;
2806
2807     public:
2808         explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
2809
2810         template <typename RhsT>
2811         auto operator==(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2812             return {compareEqual(m_lhs, rhs), m_lhs, "==", rhs};
2813         }
2814         auto operator==(bool rhs) -> BinaryExpr<LhsT, bool> const {
2815             return {m_lhs == rhs, m_lhs, "==", rhs};
2816         }
2817
2818         template <typename RhsT>
2819         auto operator!=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2820             return {compareNotEqual(m_lhs, rhs), m_lhs, "!=", rhs};
2821         }
2822         auto operator!=(bool rhs) -> BinaryExpr<LhsT, bool> const {
2823             return {m_lhs != rhs, m_lhs, "!=", rhs};
2824         }
2825
2826         template <typename RhsT>
2827         auto operator>(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2828             return {static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs};
2829         }
2830         template <typename RhsT>
2831         auto operator<(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2832             return {static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs};
2833         }
2834         template <typename RhsT>
2835         auto operator>=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2836             return {static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs};
2837         }
2838         template <typename RhsT>
2839         auto operator<=(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2840             return {static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs};
2841         }
2842         template <typename RhsT>
2843         auto operator|(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2844             return {static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs};
2845         }
2846         template <typename RhsT>
2847         auto operator&(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2848             return {static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs};
2849         }
2850         template <typename RhsT>
2851         auto operator^(RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2852             return {static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs};
2853         }
2854
2855         template <typename RhsT>
2856         auto operator&&(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2857             static_assert(always_false<RhsT>::value,
2858                           "operator&& is not supported inside assertions, "
2859                           "wrap the expression inside parentheses, or decompose it");
2860         }
2861
2862         template <typename RhsT>
2863         auto operator||(RhsT const&) -> BinaryExpr<LhsT, RhsT const&> const {
2864             static_assert(always_false<RhsT>::value,
2865                           "operator|| is not supported inside assertions, "
2866                           "wrap the expression inside parentheses, or decompose it");
2867         }
2868
2869         auto makeUnaryExpr() const -> UnaryExpr<LhsT> { return UnaryExpr<LhsT>{m_lhs}; }
2870     };
2871
2872     void handleExpression(ITransientExpression const& expr);
2873
2874     template <typename T> void handleExpression(ExprLhs<T> const& expr) {
2875         handleExpression(expr.makeUnaryExpr());
2876     }
2877
2878     struct Decomposer {
2879         template <typename T> auto operator<=(T const& lhs) -> ExprLhs<T const&> {
2880             return ExprLhs<T const&>{lhs};
2881         }
2882
2883         auto operator<=(bool value) -> ExprLhs<bool> { return ExprLhs<bool>{value}; }
2884     };
2885
2886 } // end namespace Catch
2887
2888 #ifdef _MSC_VER
2889 #pragma warning(pop)
2890 #endif
2891
2892 // end catch_decomposer.h
2893 // start catch_interfaces_capture.h
2894
2895 #include <string>
2896 #include <chrono>
2897
2898 namespace Catch {
2899
2900     class AssertionResult;
2901     struct AssertionInfo;
2902     struct SectionInfo;
2903     struct SectionEndInfo;
2904     struct MessageInfo;
2905     struct MessageBuilder;
2906     struct Counts;
2907     struct AssertionReaction;
2908     struct SourceLineInfo;
2909
2910     struct ITransientExpression;
2911     struct IGeneratorTracker;
2912
2913 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2914     struct BenchmarkInfo;
2915     template <typename Duration = std::chrono::duration<double, std::nano>> struct BenchmarkStats;
2916 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2917
2918     struct IResultCapture {
2919
2920         virtual ~IResultCapture();
2921
2922         virtual bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) = 0;
2923         virtual void sectionEnded(SectionEndInfo const& endInfo) = 0;
2924         virtual void sectionEndedEarly(SectionEndInfo const& endInfo) = 0;
2925
2926         virtual auto acquireGeneratorTracker(StringRef generatorName,
2927                                              SourceLineInfo const& lineInfo)
2928             -> IGeneratorTracker& = 0;
2929
2930 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2931         virtual void benchmarkPreparing(std::string const& name) = 0;
2932         virtual void benchmarkStarting(BenchmarkInfo const& info) = 0;
2933         virtual void benchmarkEnded(BenchmarkStats<> const& stats) = 0;
2934         virtual void benchmarkFailed(std::string const& error) = 0;
2935 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2936
2937         virtual void pushScopedMessage(MessageInfo const& message) = 0;
2938         virtual void popScopedMessage(MessageInfo const& message) = 0;
2939
2940         virtual void emplaceUnscopedMessage(MessageBuilder const& builder) = 0;
2941
2942         virtual void handleFatalErrorCondition(StringRef message) = 0;
2943
2944         virtual void handleExpr(AssertionInfo const& info,
2945                                 ITransientExpression const& expr,
2946                                 AssertionReaction& reaction) = 0;
2947         virtual void handleMessage(AssertionInfo const& info,
2948                                    ResultWas::OfType resultType,
2949                                    StringRef const& message,
2950                                    AssertionReaction& reaction) = 0;
2951         virtual void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
2952                                                         AssertionReaction& reaction) = 0;
2953         virtual void handleUnexpectedInflightException(AssertionInfo const& info,
2954                                                        std::string const& message,
2955                                                        AssertionReaction& reaction) = 0;
2956         virtual void handleIncomplete(AssertionInfo const& info) = 0;
2957         virtual void handleNonExpr(AssertionInfo const& info,
2958                                    ResultWas::OfType resultType,
2959                                    AssertionReaction& reaction) = 0;
2960
2961         virtual bool lastAssertionPassed() = 0;
2962         virtual void assertionPassed() = 0;
2963
2964         // Deprecated, do not use:
2965         virtual std::string getCurrentTestName() const = 0;
2966         virtual const AssertionResult* getLastResult() const = 0;
2967         virtual void exceptionEarlyReported() = 0;
2968     };
2969
2970     IResultCapture& getResultCapture();
2971 } // namespace Catch
2972
2973 // end catch_interfaces_capture.h
2974 namespace Catch {
2975
2976     struct TestFailureException {};
2977     struct AssertionResultData;
2978     struct IResultCapture;
2979     class RunContext;
2980
2981     class LazyExpression {
2982         friend class AssertionHandler;
2983         friend struct AssertionStats;
2984         friend class RunContext;
2985
2986         ITransientExpression const* m_transientExpression = nullptr;
2987         bool m_isNegated;
2988
2989     public:
2990         LazyExpression(bool isNegated);
2991         LazyExpression(LazyExpression const& other);
2992         LazyExpression& operator=(LazyExpression const&) = delete;
2993
2994         explicit operator bool() const;
2995
2996         friend auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream&;
2997     };
2998
2999     struct AssertionReaction {
3000         bool shouldDebugBreak = false;
3001         bool shouldThrow = false;
3002     };
3003
3004     class AssertionHandler {
3005         AssertionInfo m_assertionInfo;
3006         AssertionReaction m_reaction;
3007         bool m_completed = false;
3008         IResultCapture& m_resultCapture;
3009
3010     public:
3011         AssertionHandler(StringRef const& macroName,
3012                          SourceLineInfo const& lineInfo,
3013                          StringRef capturedExpression,
3014                          ResultDisposition::Flags resultDisposition);
3015         ~AssertionHandler() {
3016             if (!m_completed) {
3017                 m_resultCapture.handleIncomplete(m_assertionInfo);
3018             }
3019         }
3020
3021         template <typename T> void handleExpr(ExprLhs<T> const& expr) {
3022             handleExpr(expr.makeUnaryExpr());
3023         }
3024         void handleExpr(ITransientExpression const& expr);
3025
3026         void handleMessage(ResultWas::OfType resultType, StringRef const& message);
3027
3028         void handleExceptionThrownAsExpected();
3029         void handleUnexpectedExceptionNotThrown();
3030         void handleExceptionNotThrownAsExpected();
3031         void handleThrowingCallSkipped();
3032         void handleUnexpectedInflightException();
3033
3034         void complete();
3035         void setCompleted();
3036
3037         // query
3038         auto allowThrows() const -> bool;
3039     };
3040
3041     void handleExceptionMatchExpr(AssertionHandler& handler,
3042                                   std::string const& str,
3043                                   StringRef const& matcherString);
3044
3045 } // namespace Catch
3046
3047 // end catch_assertionhandler.h
3048 // start catch_message.h
3049
3050 #include <string>
3051 #include <vector>
3052
3053 namespace Catch {
3054
3055     struct MessageInfo {
3056         MessageInfo(StringRef const& _macroName,
3057                     SourceLineInfo const& _lineInfo,
3058                     ResultWas::OfType _type);
3059
3060         StringRef macroName;
3061         std::string message;
3062         SourceLineInfo lineInfo;
3063         ResultWas::OfType type;
3064         unsigned int sequence;
3065
3066         bool operator==(MessageInfo const& other) const;
3067         bool operator<(MessageInfo const& other) const;
3068
3069     private:
3070         static unsigned int globalCount;
3071     };
3072
3073     struct MessageStream {
3074
3075         template <typename T> MessageStream& operator<<(T const& value) {
3076             m_stream << value;
3077             return *this;
3078         }
3079
3080         ReusableStringStream m_stream;
3081     };
3082
3083     struct MessageBuilder : MessageStream {
3084         MessageBuilder(StringRef const& macroName,
3085                        SourceLineInfo const& lineInfo,
3086                        ResultWas::OfType type);
3087
3088         template <typename T> MessageBuilder& operator<<(T const& value) {
3089             m_stream << value;
3090             return *this;
3091         }
3092
3093         MessageInfo m_info;
3094     };
3095
3096     class ScopedMessage {
3097     public:
3098         explicit ScopedMessage(MessageBuilder const& builder);
3099         ScopedMessage(ScopedMessage& duplicate) = delete;
3100         ScopedMessage(ScopedMessage&& old);
3101         ~ScopedMessage();
3102
3103         MessageInfo m_info;
3104         bool m_moved;
3105     };
3106
3107     class Capturer {
3108         std::vector<MessageInfo> m_messages;
3109         IResultCapture& m_resultCapture = getResultCapture();
3110         size_t m_captured = 0;
3111
3112     public:
3113         Capturer(StringRef macroName,
3114                  SourceLineInfo const& lineInfo,
3115                  ResultWas::OfType resultType,
3116                  StringRef names);
3117         ~Capturer();
3118
3119         void captureValue(size_t index, std::string const& value);
3120
3121         template <typename T> void captureValues(size_t index, T const& value) {
3122             captureValue(index, Catch::Detail::stringify(value));
3123         }
3124
3125         template <typename T, typename... Ts>
3126         void captureValues(size_t index, T const& value, Ts const&... values) {
3127             captureValue(index, Catch::Detail::stringify(value));
3128             captureValues(index + 1, values...);
3129         }
3130     };
3131
3132 } // end namespace Catch
3133
3134 // end catch_message.h
3135 #if !defined(CATCH_CONFIG_DISABLE)
3136
3137 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
3138 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
3139 #else
3140 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
3141 #endif
3142
3143 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3144
3145 ///////////////////////////////////////////////////////////////////////////////
3146 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
3147 // macros.
3148 #define INTERNAL_CATCH_TRY
3149 #define INTERNAL_CATCH_CATCH(capturer)
3150
3151 #else // CATCH_CONFIG_FAST_COMPILE
3152
3153 #define INTERNAL_CATCH_TRY try
3154 #define INTERNAL_CATCH_CATCH(handler)                                                              \
3155     catch (...) {                                                                                  \
3156         handler.handleUnexpectedInflightException();                                               \
3157     }
3158
3159 #endif
3160
3161 #define INTERNAL_CATCH_REACT(handler) handler.complete();
3162
3163 ///////////////////////////////////////////////////////////////////////////////
3164 #define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...)                                     \
3165     do {                                                                                           \
3166         CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__);                                               \
3167         Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr,                        \
3168                                                       CATCH_INTERNAL_LINEINFO,                     \
3169                                                       CATCH_INTERNAL_STRINGIFY(__VA_ARGS__),       \
3170                                                       resultDisposition);                          \
3171         INTERNAL_CATCH_TRY {                                                                       \
3172             CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                              \
3173             CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS                                           \
3174             catchAssertionHandler.handleExpr(Catch::Decomposer() <= __VA_ARGS__);                  \
3175             CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                               \
3176         }                                                                                          \
3177         INTERNAL_CATCH_CATCH(catchAssertionHandler)                                                \
3178         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3179     } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__)))
3180
3181 ///////////////////////////////////////////////////////////////////////////////
3182 #define INTERNAL_CATCH_IF(macroName, resultDisposition, ...)                                       \
3183     INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__);                                \
3184     if (Catch::getResultCapture().lastAssertionPassed())
3185
3186 ///////////////////////////////////////////////////////////////////////////////
3187 #define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...)                                     \
3188     INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__);                                \
3189     if (!Catch::getResultCapture().lastAssertionPassed())
3190
3191 ///////////////////////////////////////////////////////////////////////////////
3192 #define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...)                                 \
3193     do {                                                                                           \
3194         Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr,                        \
3195                                                       CATCH_INTERNAL_LINEINFO,                     \
3196                                                       CATCH_INTERNAL_STRINGIFY(__VA_ARGS__),       \
3197                                                       resultDisposition);                          \
3198         try {                                                                                      \
3199             static_cast<void>(__VA_ARGS__);                                                        \
3200             catchAssertionHandler.handleExceptionNotThrownAsExpected();                            \
3201         } catch (...) {                                                                            \
3202             catchAssertionHandler.handleUnexpectedInflightException();                             \
3203         }                                                                                          \
3204         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3205     } while (false)
3206
3207 ///////////////////////////////////////////////////////////////////////////////
3208 #define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...)                                   \
3209     do {                                                                                           \
3210         Catch::AssertionHandler catchAssertionHandler(macroName##_catch_sr,                        \
3211                                                       CATCH_INTERNAL_LINEINFO,                     \
3212                                                       CATCH_INTERNAL_STRINGIFY(__VA_ARGS__),       \
3213                                                       resultDisposition);                          \
3214         if (catchAssertionHandler.allowThrows())                                                   \
3215             try {                                                                                  \
3216                 static_cast<void>(__VA_ARGS__);                                                    \
3217                 catchAssertionHandler.handleUnexpectedExceptionNotThrown();                        \
3218             } catch (...) {                                                                        \
3219                 catchAssertionHandler.handleExceptionThrownAsExpected();                           \
3220             }                                                                                      \
3221         else                                                                                       \
3222             catchAssertionHandler.handleThrowingCallSkipped();                                     \
3223         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3224     } while (false)
3225
3226 ///////////////////////////////////////////////////////////////////////////////
3227 #define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr)                \
3228     do {                                                                                           \
3229         Catch::AssertionHandler catchAssertionHandler(                                             \
3230             macroName##_catch_sr,                                                                  \
3231             CATCH_INTERNAL_LINEINFO,                                                               \
3232             CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType),           \
3233             resultDisposition);                                                                    \
3234         if (catchAssertionHandler.allowThrows())                                                   \
3235             try {                                                                                  \
3236                 static_cast<void>(expr);                                                           \
3237                 catchAssertionHandler.handleUnexpectedExceptionNotThrown();                        \
3238             } catch (exceptionType const&) {                                                       \
3239                 catchAssertionHandler.handleExceptionThrownAsExpected();                           \
3240             } catch (...) {                                                                        \
3241                 catchAssertionHandler.handleUnexpectedInflightException();                         \
3242             }                                                                                      \
3243         else                                                                                       \
3244             catchAssertionHandler.handleThrowingCallSkipped();                                     \
3245         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3246     } while (false)
3247
3248 ///////////////////////////////////////////////////////////////////////////////
3249 #define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...)                         \
3250     do {                                                                                           \
3251         Catch::AssertionHandler catchAssertionHandler(                                             \
3252             macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition); \
3253         catchAssertionHandler.handleMessage(                                                       \
3254             messageType,                                                                           \
3255             (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()).m_stream.str());    \
3256         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3257     } while (false)
3258
3259 ///////////////////////////////////////////////////////////////////////////////
3260 #define INTERNAL_CATCH_CAPTURE(varName, macroName, ...)                                            \
3261     auto varName =                                                                                 \
3262         Catch::Capturer(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__); \
3263     varName.captureValues(0, __VA_ARGS__)
3264
3265 ///////////////////////////////////////////////////////////////////////////////
3266 #define INTERNAL_CATCH_INFO(macroName, log)                                                        \
3267     Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)(                                \
3268         Catch::MessageBuilder(                                                                     \
3269             macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info)                 \
3270         << log);
3271
3272 ///////////////////////////////////////////////////////////////////////////////
3273 #define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log)                                               \
3274     Catch::getResultCapture().emplaceUnscopedMessage(                                              \
3275         Catch::MessageBuilder(                                                                     \
3276             macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info)                 \
3277         << log)
3278
3279 ///////////////////////////////////////////////////////////////////////////////
3280 // Although this is matcher-based, it can be used with just a string
3281 #define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...)              \
3282     do {                                                                                           \
3283         Catch::AssertionHandler catchAssertionHandler(                                             \
3284             macroName##_catch_sr,                                                                  \
3285             CATCH_INTERNAL_LINEINFO,                                                               \
3286             CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher),          \
3287             resultDisposition);                                                                    \
3288         if (catchAssertionHandler.allowThrows())                                                   \
3289             try {                                                                                  \
3290                 static_cast<void>(__VA_ARGS__);                                                    \
3291                 catchAssertionHandler.handleUnexpectedExceptionNotThrown();                        \
3292             } catch (...) {                                                                        \
3293                 Catch::handleExceptionMatchExpr(                                                   \
3294                     catchAssertionHandler, matcher, #matcher##_catch_sr);                          \
3295             }                                                                                      \
3296         else                                                                                       \
3297             catchAssertionHandler.handleThrowingCallSkipped();                                     \
3298         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
3299     } while (false)
3300
3301 #endif // CATCH_CONFIG_DISABLE
3302
3303 // end catch_capture.hpp
3304 // start catch_section.h
3305
3306 // start catch_section_info.h
3307
3308 // start catch_totals.h
3309
3310 #include <cstddef>
3311
3312 namespace Catch {
3313
3314     struct Counts {
3315         Counts operator-(Counts const& other) const;
3316         Counts& operator+=(Counts const& other);
3317
3318         std::size_t total() const;
3319         bool allPassed() const;
3320         bool allOk() const;
3321
3322         std::size_t passed = 0;
3323         std::size_t failed = 0;
3324         std::size_t failedButOk = 0;
3325     };
3326
3327     struct Totals {
3328
3329         Totals operator-(Totals const& other) const;
3330         Totals& operator+=(Totals const& other);
3331
3332         Totals delta(Totals const& prevTotals) const;
3333
3334         int error = 0;
3335         Counts assertions;
3336         Counts testCases;
3337     };
3338 } // namespace Catch
3339
3340 // end catch_totals.h
3341 #include <string>
3342
3343 namespace Catch {
3344
3345     struct SectionInfo {
3346         SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name);
3347
3348         // Deprecated
3349         SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name, std::string const&) :
3350             SectionInfo(_lineInfo, _name) {}
3351
3352         std::string name;
3353         std::string description; // !Deprecated: this will always be empty
3354         SourceLineInfo lineInfo;
3355     };
3356
3357     struct SectionEndInfo {
3358         SectionInfo sectionInfo;
3359         Counts prevAssertions;
3360         double durationInSeconds;
3361     };
3362
3363 } // end namespace Catch
3364
3365 // end catch_section_info.h
3366 // start catch_timer.h
3367
3368 #include <cstdint>
3369
3370 namespace Catch {
3371
3372     auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
3373     auto getEstimatedClockResolution() -> uint64_t;
3374
3375     class Timer {
3376         uint64_t m_nanoseconds = 0;
3377
3378     public:
3379         void start();
3380         auto getElapsedNanoseconds() const -> uint64_t;
3381         auto getElapsedMicroseconds() const -> uint64_t;
3382         auto getElapsedMilliseconds() const -> unsigned int;
3383         auto getElapsedSeconds() const -> double;
3384     };
3385
3386 } // namespace Catch
3387
3388 // end catch_timer.h
3389 #include <string>
3390
3391 namespace Catch {
3392
3393     class Section : NonCopyable {
3394     public:
3395         Section(SectionInfo const& info);
3396         ~Section();
3397
3398         // This indicates whether the section should be executed or not
3399         explicit operator bool() const;
3400
3401     private:
3402         SectionInfo m_info;
3403
3404         std::string m_name;
3405         Counts m_assertions;
3406         bool m_sectionIncluded;
3407         Timer m_timer;
3408     };
3409
3410 } // end namespace Catch
3411
3412 #define INTERNAL_CATCH_SECTION(...)                                                                \
3413     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
3414     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS                                                        \
3415     if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) =                 \
3416             Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__))                              \
3417     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3418
3419 #define INTERNAL_CATCH_DYNAMIC_SECTION(...)                                                        \
3420     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
3421     CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS                                                        \
3422     if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) =                 \
3423             Catch::SectionInfo(CATCH_INTERNAL_LINEINFO,                                            \
3424                                (Catch::ReusableStringStream() << __VA_ARGS__).str()))              \
3425     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3426
3427 // end catch_section.h
3428 // start catch_interfaces_exception.h
3429
3430 // start catch_interfaces_registry_hub.h
3431
3432 #include <string>
3433 #include <memory>
3434
3435 namespace Catch {
3436
3437     class TestCase;
3438     struct ITestCaseRegistry;
3439     struct IExceptionTranslatorRegistry;
3440     struct IExceptionTranslator;
3441     struct IReporterRegistry;
3442     struct IReporterFactory;
3443     struct ITagAliasRegistry;
3444     struct IMutableEnumValuesRegistry;
3445
3446     class StartupExceptionRegistry;
3447
3448     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
3449
3450     struct IRegistryHub {
3451         virtual ~IRegistryHub();
3452
3453         virtual IReporterRegistry const& getReporterRegistry() const = 0;
3454         virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
3455         virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
3456         virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
3457
3458         virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
3459     };
3460
3461     struct IMutableRegistryHub {
3462         virtual ~IMutableRegistryHub();
3463         virtual void registerReporter(std::string const& name,
3464                                       IReporterFactoryPtr const& factory) = 0;
3465         virtual void registerListener(IReporterFactoryPtr const& factory) = 0;
3466         virtual void registerTest(TestCase const& testInfo) = 0;
3467         virtual void registerTranslator(const IExceptionTranslator* translator) = 0;
3468         virtual void registerTagAlias(std::string const& alias,
3469                                       std::string const& tag,
3470                                       SourceLineInfo const& lineInfo) = 0;
3471         virtual void registerStartupException() noexcept = 0;
3472         virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
3473     };
3474
3475     IRegistryHub const& getRegistryHub();
3476     IMutableRegistryHub& getMutableRegistryHub();
3477     void cleanUp();
3478     std::string translateActiveException();
3479
3480 } // namespace Catch
3481
3482 // end catch_interfaces_registry_hub.h
3483 #if defined(CATCH_CONFIG_DISABLE)
3484 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature)                       \
3485     static std::string translatorName(signature)
3486 #endif
3487
3488 #include <exception>
3489 #include <string>
3490 #include <vector>
3491
3492 namespace Catch {
3493     using exceptionTranslateFunction = std::string (*)();
3494
3495     struct IExceptionTranslator;
3496     using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3497
3498     struct IExceptionTranslator {
3499         virtual ~IExceptionTranslator();
3500         virtual std::string translate(ExceptionTranslators::const_iterator it,
3501                                       ExceptionTranslators::const_iterator itEnd) const = 0;
3502     };
3503
3504     struct IExceptionTranslatorRegistry {
3505         virtual ~IExceptionTranslatorRegistry();
3506
3507         virtual std::string translateActiveException() const = 0;
3508     };
3509
3510     class ExceptionTranslatorRegistrar {
3511         template <typename T> class ExceptionTranslator : public IExceptionTranslator {
3512         public:
3513             ExceptionTranslator(std::string (*translateFunction)(T&)) :
3514                 m_translateFunction(translateFunction) {}
3515
3516             std::string translate(ExceptionTranslators::const_iterator it,
3517                                   ExceptionTranslators::const_iterator itEnd) const override {
3518 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3519                 return "";
3520 #else
3521                 try {
3522                     if (it == itEnd)
3523                         std::rethrow_exception(std::current_exception());
3524                     else
3525                         return (*it)->translate(it + 1, itEnd);
3526                 } catch (T& ex) {
3527                     return m_translateFunction(ex);
3528                 }
3529 #endif
3530             }
3531
3532         protected:
3533             std::string (*m_translateFunction)(T&);
3534         };
3535
3536     public:
3537         template <typename T> ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) {
3538             getMutableRegistryHub().registerTranslator(
3539                 new ExceptionTranslator<T>(translateFunction));
3540         }
3541     };
3542 } // namespace Catch
3543
3544 ///////////////////////////////////////////////////////////////////////////////
3545 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature)                             \
3546     static std::string translatorName(signature);                                                  \
3547     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
3548     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
3549     namespace {                                                                                    \
3550         Catch::ExceptionTranslatorRegistrar                                                        \
3551             INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName);        \
3552     }                                                                                              \
3553     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION                                                       \
3554     static std::string translatorName(signature)
3555
3556 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)                                              \
3557     INTERNAL_CATCH_TRANSLATE_EXCEPTION2(                                                           \
3558         INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
3559
3560 // end catch_interfaces_exception.h
3561 // start catch_approx.h
3562
3563 #include <type_traits>
3564
3565 namespace Catch {
3566     namespace Detail {
3567
3568         class Approx {
3569         private:
3570             bool equalityComparisonImpl(double other) const;
3571             // Validates the new margin (margin >= 0)
3572             // out-of-line to avoid including stdexcept in the header
3573             void setMargin(double margin);
3574             // Validates the new epsilon (0 < epsilon < 1)
3575             // out-of-line to avoid including stdexcept in the header
3576             void setEpsilon(double epsilon);
3577
3578         public:
3579             explicit Approx(double value);
3580
3581             static Approx custom();
3582
3583             Approx operator-() const;
3584
3585             template <
3586                 typename T,
3587                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3588             Approx operator()(T const& value) {
3589                 Approx approx(static_cast<double>(value));
3590                 approx.m_epsilon = m_epsilon;
3591                 approx.m_margin = m_margin;
3592                 approx.m_scale = m_scale;
3593                 return approx;
3594             }
3595
3596             template <
3597                 typename T,
3598                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3599             explicit Approx(T const& value) : Approx(static_cast<double>(value)) {}
3600
3601             template <
3602                 typename T,
3603                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3604             friend bool operator==(const T& lhs, Approx const& rhs) {
3605                 auto lhs_v = static_cast<double>(lhs);
3606                 return rhs.equalityComparisonImpl(lhs_v);
3607             }
3608
3609             template <
3610                 typename T,
3611                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3612             friend bool operator==(Approx const& lhs, const T& rhs) {
3613                 return operator==(rhs, lhs);
3614             }
3615
3616             template <
3617                 typename T,
3618                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3619             friend bool operator!=(T const& lhs, Approx const& rhs) {
3620                 return !operator==(lhs, rhs);
3621             }
3622
3623             template <
3624                 typename T,
3625                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3626             friend bool operator!=(Approx const& lhs, T const& rhs) {
3627                 return !operator==(rhs, lhs);
3628             }
3629
3630             template <
3631                 typename T,
3632                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3633             friend bool operator<=(T const& lhs, Approx const& rhs) {
3634                 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3635             }
3636
3637             template <
3638                 typename T,
3639                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3640             friend bool operator<=(Approx const& lhs, T const& rhs) {
3641                 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3642             }
3643
3644             template <
3645                 typename T,
3646                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3647             friend bool operator>=(T const& lhs, Approx const& rhs) {
3648                 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3649             }
3650
3651             template <
3652                 typename T,
3653                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3654             friend bool operator>=(Approx const& lhs, T const& rhs) {
3655                 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3656             }
3657
3658             template <
3659                 typename T,
3660                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3661             Approx& epsilon(T const& newEpsilon) {
3662                 double epsilonAsDouble = static_cast<double>(newEpsilon);
3663                 setEpsilon(epsilonAsDouble);
3664                 return *this;
3665             }
3666
3667             template <
3668                 typename T,
3669                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3670             Approx& margin(T const& newMargin) {
3671                 double marginAsDouble = static_cast<double>(newMargin);
3672                 setMargin(marginAsDouble);
3673                 return *this;
3674             }
3675
3676             template <
3677                 typename T,
3678                 typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3679             Approx& scale(T const& newScale) {
3680                 m_scale = static_cast<double>(newScale);
3681                 return *this;
3682             }
3683
3684             std::string toString() const;
3685
3686         private:
3687             double m_epsilon;
3688             double m_margin;
3689             double m_scale;
3690             double m_value;
3691         };
3692     } // end namespace Detail
3693
3694     namespace literals {
3695         Detail::Approx operator"" _a(long double val);
3696         Detail::Approx operator"" _a(unsigned long long val);
3697     } // end namespace literals
3698
3699     template <> struct StringMaker<Catch::Detail::Approx> {
3700         static std::string convert(Catch::Detail::Approx const& value);
3701     };
3702
3703 } // end namespace Catch
3704
3705 // end catch_approx.h
3706 // start catch_string_manip.h
3707
3708 #include <string>
3709 #include <iosfwd>
3710 #include <vector>
3711
3712 namespace Catch {
3713
3714     bool startsWith(std::string const& s, std::string const& prefix);
3715     bool startsWith(std::string const& s, char prefix);
3716     bool endsWith(std::string const& s, std::string const& suffix);
3717     bool endsWith(std::string const& s, char suffix);
3718     bool contains(std::string const& s, std::string const& infix);
3719     void toLowerInPlace(std::string& s);
3720     std::string toLower(std::string const& s);
3721     //! Returns a new string without whitespace at the start/end
3722     std::string trim(std::string const& str);
3723     //! Returns a substring of the original ref without whitespace. Beware
3724     //! lifetimes!
3725     StringRef trim(StringRef ref);
3726
3727     // !!! Be aware, returns refs into original string - make sure original
3728     // string outlives them
3729     std::vector<StringRef> splitStringRef(StringRef str, char delimiter);
3730     bool
3731     replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis);
3732
3733     struct pluralise {
3734         pluralise(std::size_t count, std::string const& label);
3735
3736         friend std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser);
3737
3738         std::size_t m_count;
3739         std::string m_label;
3740     };
3741 } // namespace Catch
3742
3743 // end catch_string_manip.h
3744 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3745 // start catch_capture_matchers.h
3746
3747 // start catch_matchers.h
3748
3749 #include <string>
3750 #include <vector>
3751
3752 namespace Catch {
3753     namespace Matchers {
3754         namespace Impl {
3755
3756             template <typename ArgT> struct MatchAllOf;
3757             template <typename ArgT> struct MatchAnyOf;
3758             template <typename ArgT> struct MatchNotOf;
3759
3760             class MatcherUntypedBase {
3761             public:
3762                 MatcherUntypedBase() = default;
3763                 MatcherUntypedBase(MatcherUntypedBase const&) = default;
3764                 MatcherUntypedBase& operator=(MatcherUntypedBase const&) = delete;
3765                 std::string toString() const;
3766
3767             protected:
3768                 virtual ~MatcherUntypedBase();
3769                 virtual std::string describe() const = 0;
3770                 mutable std::string m_cachedToString;
3771             };
3772
3773 #ifdef __clang__
3774 #pragma clang diagnostic push
3775 #pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3776 #endif
3777
3778             template <typename ObjectT> struct MatcherMethod {
3779                 virtual bool match(ObjectT const& arg) const = 0;
3780             };
3781
3782 #if defined(__OBJC__)
3783             // Hack to fix Catch GH issue #1661. Could use id for generic Object
3784             // support. use of const for Object pointers is very uncommon and
3785             // under ARC it causes some kind of signature mismatch that breaks
3786             // compilation
3787             template <> struct MatcherMethod<NSString*> {
3788                 virtual bool match(NSString* arg) const = 0;
3789             };
3790 #endif
3791
3792 #ifdef __clang__
3793 #pragma clang diagnostic pop
3794 #endif
3795
3796             template <typename T> struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3797
3798                 MatchAllOf<T> operator&&(MatcherBase const& other) const;
3799                 MatchAnyOf<T> operator||(MatcherBase const& other) const;
3800                 MatchNotOf<T> operator!() const;
3801             };
3802
3803             template <typename ArgT> struct MatchAllOf : MatcherBase<ArgT> {
3804                 bool match(ArgT const& arg) const override {
3805                     for (auto matcher : m_matchers) {
3806                         if (!matcher->match(arg))
3807                             return false;
3808                     }
3809                     return true;
3810                 }
3811                 std::string describe() const override {
3812                     std::string description;
3813                     description.reserve(4 + m_matchers.size() * 32);
3814                     description += "( ";
3815                     bool first = true;
3816                     for (auto matcher : m_matchers) {
3817                         if (first)
3818                             first = false;
3819                         else
3820                             description += " and ";
3821                         description += matcher->toString();
3822                     }
3823                     description += " )";
3824                     return description;
3825                 }
3826
3827                 MatchAllOf<ArgT> operator&&(MatcherBase<ArgT> const& other) {
3828                     auto copy(*this);
3829                     copy.m_matchers.push_back(&other);
3830                     return copy;
3831                 }
3832
3833                 std::vector<MatcherBase<ArgT> const*> m_matchers;
3834             };
3835             template <typename ArgT> struct MatchAnyOf : MatcherBase<ArgT> {
3836
3837                 bool match(ArgT const& arg) const override {
3838                     for (auto matcher : m_matchers) {
3839                         if (matcher->match(arg))
3840                             return true;
3841                     }
3842                     return false;
3843                 }
3844                 std::string describe() const override {
3845                     std::string description;
3846                     description.reserve(4 + m_matchers.size() * 32);
3847                     description += "( ";
3848                     bool first = true;
3849                     for (auto matcher : m_matchers) {
3850                         if (first)
3851                             first = false;
3852                         else
3853                             description += " or ";
3854                         description += matcher->toString();
3855                     }
3856                     description += " )";
3857                     return description;
3858                 }
3859
3860                 MatchAnyOf<ArgT> operator||(MatcherBase<ArgT> const& other) {
3861                     auto copy(*this);
3862                     copy.m_matchers.push_back(&other);
3863                     return copy;
3864                 }
3865
3866                 std::vector<MatcherBase<ArgT> const*> m_matchers;
3867             };
3868
3869             template <typename ArgT> struct MatchNotOf : MatcherBase<ArgT> {
3870
3871                 MatchNotOf(MatcherBase<ArgT> const& underlyingMatcher) :
3872                     m_underlyingMatcher(underlyingMatcher) {}
3873
3874                 bool match(ArgT const& arg) const override {
3875                     return !m_underlyingMatcher.match(arg);
3876                 }
3877
3878                 std::string describe() const override {
3879                     return "not " + m_underlyingMatcher.toString();
3880                 }
3881                 MatcherBase<ArgT> const& m_underlyingMatcher;
3882             };
3883
3884             template <typename T>
3885             MatchAllOf<T> MatcherBase<T>::operator&&(MatcherBase const& other) const {
3886                 return MatchAllOf<T>() && *this && other;
3887             }
3888             template <typename T>
3889             MatchAnyOf<T> MatcherBase<T>::operator||(MatcherBase const& other) const {
3890                 return MatchAnyOf<T>() || *this || other;
3891             }
3892             template <typename T> MatchNotOf<T> MatcherBase<T>::operator!() const {
3893                 return MatchNotOf<T>(*this);
3894             }
3895
3896         } // namespace Impl
3897
3898     } // namespace Matchers
3899
3900     using namespace Matchers;
3901     using Matchers::Impl::MatcherBase;
3902
3903 } // namespace Catch
3904
3905 // end catch_matchers.h
3906 // start catch_matchers_exception.hpp
3907
3908 namespace Catch {
3909     namespace Matchers {
3910         namespace Exception {
3911
3912             class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3913                 std::string m_message;
3914
3915             public:
3916                 ExceptionMessageMatcher(std::string const& message) : m_message(message) {}
3917
3918                 bool match(std::exception const& ex) const override;
3919
3920                 std::string describe() const override;
3921             };
3922
3923         } // namespace Exception
3924
3925         Exception::ExceptionMessageMatcher Message(std::string const& message);
3926
3927     } // namespace Matchers
3928 } // namespace Catch
3929
3930 // end catch_matchers_exception.hpp
3931 // start catch_matchers_floating.h
3932
3933 namespace Catch {
3934     namespace Matchers {
3935
3936         namespace Floating {
3937
3938             enum class FloatingPointKind : uint8_t;
3939
3940             struct WithinAbsMatcher : MatcherBase<double> {
3941                 WithinAbsMatcher(double target, double margin);
3942                 bool match(double const& matchee) const override;
3943                 std::string describe() const override;
3944
3945             private:
3946                 double m_target;
3947                 double m_margin;
3948             };
3949
3950             struct WithinUlpsMatcher : MatcherBase<double> {
3951                 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3952                 bool match(double const& matchee) const override;
3953                 std::string describe() const override;
3954
3955             private:
3956                 double m_target;
3957                 uint64_t m_ulps;
3958                 FloatingPointKind m_type;
3959             };
3960
3961             // Given IEEE-754 format for floats and doubles, we can assume
3962             // that float -> double promotion is lossless. Given this, we can
3963             // assume that if we do the standard relative comparison of
3964             // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3965             // the same result if we do this for floats, as if we do this for
3966             // doubles that were promoted from floats.
3967             struct WithinRelMatcher : MatcherBase<double> {
3968                 WithinRelMatcher(double target, double epsilon);
3969                 bool match(double const& matchee) const override;
3970                 std::string describe() const override;
3971
3972             private:
3973                 double m_target;
3974                 double m_epsilon;
3975             };
3976
3977         } // namespace Floating
3978
3979         // The following functions create the actual matcher objects.
3980         // This allows the types to be inferred
3981         Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3982         Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3983         Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3984         Floating::WithinRelMatcher WithinRel(double target, double eps);
3985         // defaults epsilon to 100*numeric_limits<double>::epsilon()
3986         Floating::WithinRelMatcher WithinRel(double target);
3987         Floating::WithinRelMatcher WithinRel(float target, float eps);
3988         // defaults epsilon to 100*numeric_limits<float>::epsilon()
3989         Floating::WithinRelMatcher WithinRel(float target);
3990
3991     } // namespace Matchers
3992 } // namespace Catch
3993
3994 // end catch_matchers_floating.h
3995 // start catch_matchers_generic.hpp
3996
3997 #include <functional>
3998 #include <string>
3999
4000 namespace Catch {
4001     namespace Matchers {
4002         namespace Generic {
4003
4004             namespace Detail {
4005                 std::string finalizeDescription(const std::string& desc);
4006             }
4007
4008             template <typename T> class PredicateMatcher : public MatcherBase<T> {
4009                 std::function<bool(T const&)> m_predicate;
4010                 std::string m_description;
4011
4012             public:
4013                 PredicateMatcher(std::function<bool(T const&)> const& elem,
4014                                  std::string const& descr) :
4015                     m_predicate(std::move(elem)),
4016                     m_description(Detail::finalizeDescription(descr)) {}
4017
4018                 bool match(T const& item) const override { return m_predicate(item); }
4019
4020                 std::string describe() const override { return m_description; }
4021             };
4022
4023         } // namespace Generic
4024
4025         // The following functions create the actual matcher objects.
4026         // The user has to explicitly specify type to the function, because
4027         // inferring std::function<bool(T const&)> is hard (but possible) and
4028         // requires a lot of TMP.
4029         template <typename T>
4030         Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate,
4031                                                std::string const& description = "") {
4032             return Generic::PredicateMatcher<T>(predicate, description);
4033         }
4034
4035     } // namespace Matchers
4036 } // namespace Catch
4037
4038 // end catch_matchers_generic.hpp
4039 // start catch_matchers_string.h
4040
4041 #include <string>
4042
4043 namespace Catch {
4044     namespace Matchers {
4045
4046         namespace StdString {
4047
4048             struct CasedString {
4049                 CasedString(std::string const& str, CaseSensitive::Choice caseSensitivity);
4050                 std::string adjustString(std::string const& str) const;
4051                 std::string caseSensitivitySuffix() const;
4052
4053                 CaseSensitive::Choice m_caseSensitivity;
4054                 std::string m_str;
4055             };
4056
4057             struct StringMatcherBase : MatcherBase<std::string> {
4058                 StringMatcherBase(std::string const& operation, CasedString const& comparator);
4059                 std::string describe() const override;
4060
4061                 CasedString m_comparator;
4062                 std::string m_operation;
4063             };
4064
4065             struct EqualsMatcher : StringMatcherBase {
4066                 EqualsMatcher(CasedString const& comparator);
4067                 bool match(std::string const& source) const override;
4068             };
4069             struct ContainsMatcher : StringMatcherBase {
4070                 ContainsMatcher(CasedString const& comparator);
4071                 bool match(std::string const& source) const override;
4072             };
4073             struct StartsWithMatcher : StringMatcherBase {
4074                 StartsWithMatcher(CasedString const& comparator);
4075                 bool match(std::string const& source) const override;
4076             };
4077             struct EndsWithMatcher : StringMatcherBase {
4078                 EndsWithMatcher(CasedString const& comparator);
4079                 bool match(std::string const& source) const override;
4080             };
4081
4082             struct RegexMatcher : MatcherBase<std::string> {
4083                 RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
4084                 bool match(std::string const& matchee) const override;
4085                 std::string describe() const override;
4086
4087             private:
4088                 std::string m_regex;
4089                 CaseSensitive::Choice m_caseSensitivity;
4090             };
4091
4092         } // namespace StdString
4093
4094         // The following functions create the actual matcher objects.
4095         // This allows the types to be inferred
4096
4097         StdString::EqualsMatcher Equals(std::string const& str,
4098                                         CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4099         StdString::ContainsMatcher
4100         Contains(std::string const& str,
4101                  CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4102         StdString::EndsWithMatcher
4103         EndsWith(std::string const& str,
4104                  CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4105         StdString::StartsWithMatcher
4106         StartsWith(std::string const& str,
4107                    CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4108         StdString::RegexMatcher Matches(std::string const& regex,
4109                                         CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
4110
4111     } // namespace Matchers
4112 } // namespace Catch
4113
4114 // end catch_matchers_string.h
4115 // start catch_matchers_vector.h
4116
4117 #include <algorithm>
4118
4119 namespace Catch {
4120     namespace Matchers {
4121
4122         namespace Vector {
4123             template <typename T, typename Alloc>
4124             struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
4125
4126                 ContainsElementMatcher(T const& comparator) : m_comparator(comparator) {}
4127
4128                 bool match(std::vector<T, Alloc> const& v) const override {
4129                     for (auto const& el : v) {
4130                         if (el == m_comparator) {
4131                             return true;
4132                         }
4133                     }
4134                     return false;
4135                 }
4136
4137                 std::string describe() const override {
4138                     return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4139                 }
4140
4141                 T const& m_comparator;
4142             };
4143
4144             template <typename T, typename AllocComp, typename AllocMatch>
4145             struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4146
4147                 ContainsMatcher(std::vector<T, AllocComp> const& comparator) :
4148                     m_comparator(comparator) {}
4149
4150                 bool match(std::vector<T, AllocMatch> const& v) const override {
4151                     // !TBD: see note in EqualsMatcher
4152                     if (m_comparator.size() > v.size())
4153                         return false;
4154                     for (auto const& comparator : m_comparator) {
4155                         auto present = false;
4156                         for (const auto& el : v) {
4157                             if (el == comparator) {
4158                                 present = true;
4159                                 break;
4160                             }
4161                         }
4162                         if (!present) {
4163                             return false;
4164                         }
4165                     }
4166                     return true;
4167                 }
4168                 std::string describe() const override {
4169                     return "Contains: " + ::Catch::Detail::stringify(m_comparator);
4170                 }
4171
4172                 std::vector<T, AllocComp> const& m_comparator;
4173             };
4174
4175             template <typename T, typename AllocComp, typename AllocMatch>
4176             struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4177
4178                 EqualsMatcher(std::vector<T, AllocComp> const& comparator) :
4179                     m_comparator(comparator) {}
4180
4181                 bool match(std::vector<T, AllocMatch> const& v) const override {
4182                     // !TBD: This currently works if all elements can be
4183                     // compared using !=
4184                     // - a more general approach would be via a compare template
4185                     // that defaults to using !=. but could be specialised for,
4186                     // e.g. std::vector<T, Alloc> etc
4187                     // - then just call that directly
4188                     if (m_comparator.size() != v.size())
4189                         return false;
4190                     for (std::size_t i = 0; i < v.size(); ++i)
4191                         if (m_comparator[i] != v[i])
4192                             return false;
4193                     return true;
4194                 }
4195                 std::string describe() const override {
4196                     return "Equals: " + ::Catch::Detail::stringify(m_comparator);
4197                 }
4198                 std::vector<T, AllocComp> const& m_comparator;
4199             };
4200
4201             template <typename T, typename AllocComp, typename AllocMatch>
4202             struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4203
4204                 ApproxMatcher(std::vector<T, AllocComp> const& comparator) :
4205                     m_comparator(comparator) {}
4206
4207                 bool match(std::vector<T, AllocMatch> const& v) const override {
4208                     if (m_comparator.size() != v.size())
4209                         return false;
4210                     for (std::size_t i = 0; i < v.size(); ++i)
4211                         if (m_comparator[i] != approx(v[i]))
4212                             return false;
4213                     return true;
4214                 }
4215                 std::string describe() const override {
4216                     return "is approx: " + ::Catch::Detail::stringify(m_comparator);
4217                 }
4218                 template <typename = typename std::enable_if<
4219                               std::is_constructible<double, T>::value>::type>
4220                 ApproxMatcher& epsilon(T const& newEpsilon) {
4221                     approx.epsilon(newEpsilon);
4222                     return *this;
4223                 }
4224                 template <typename = typename std::enable_if<
4225                               std::is_constructible<double, T>::value>::type>
4226                 ApproxMatcher& margin(T const& newMargin) {
4227                     approx.margin(newMargin);
4228                     return *this;
4229                 }
4230                 template <typename = typename std::enable_if<
4231                               std::is_constructible<double, T>::value>::type>
4232                 ApproxMatcher& scale(T const& newScale) {
4233                     approx.scale(newScale);
4234                     return *this;
4235                 }
4236
4237                 std::vector<T, AllocComp> const& m_comparator;
4238                 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
4239             };
4240
4241             template <typename T, typename AllocComp, typename AllocMatch>
4242             struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
4243                 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) :
4244                     m_target(target) {}
4245                 bool match(std::vector<T, AllocMatch> const& vec) const override {
4246                     if (m_target.size() != vec.size()) {
4247                         return false;
4248                     }
4249                     return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
4250                 }
4251
4252                 std::string describe() const override {
4253                     return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
4254                 }
4255
4256             private:
4257                 std::vector<T, AllocComp> const& m_target;
4258             };
4259
4260         } // namespace Vector
4261
4262         // The following functions create the actual matcher objects.
4263         // This allows the types to be inferred
4264
4265         template <typename T,
4266                   typename AllocComp = std::allocator<T>,
4267                   typename AllocMatch = AllocComp>
4268         Vector::ContainsMatcher<T, AllocComp, AllocMatch>
4269         Contains(std::vector<T, AllocComp> const& comparator) {
4270             return Vector::ContainsMatcher<T, AllocComp, AllocMatch>(comparator);
4271         }
4272
4273         template <typename T, typename Alloc = std::allocator<T>>
4274         Vector::ContainsElementMatcher<T, Alloc> VectorContains(T const& comparator) {
4275             return Vector::ContainsElementMatcher<T, Alloc>(comparator);
4276         }
4277
4278         template <typename T,
4279                   typename AllocComp = std::allocator<T>,
4280                   typename AllocMatch = AllocComp>
4281         Vector::EqualsMatcher<T, AllocComp, AllocMatch>
4282         Equals(std::vector<T, AllocComp> const& comparator) {
4283             return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
4284         }
4285
4286         template <typename T,
4287                   typename AllocComp = std::allocator<T>,
4288                   typename AllocMatch = AllocComp>
4289         Vector::ApproxMatcher<T, AllocComp, AllocMatch>
4290         Approx(std::vector<T, AllocComp> const& comparator) {
4291             return Vector::ApproxMatcher<T, AllocComp, AllocMatch>(comparator);
4292         }
4293
4294         template <typename T,
4295                   typename AllocComp = std::allocator<T>,
4296                   typename AllocMatch = AllocComp>
4297         Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>
4298         UnorderedEquals(std::vector<T, AllocComp> const& target) {
4299             return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>(target);
4300         }
4301
4302     } // namespace Matchers
4303 } // namespace Catch
4304
4305 // end catch_matchers_vector.h
4306 namespace Catch {
4307
4308     template <typename ArgT, typename MatcherT> class MatchExpr : public ITransientExpression {
4309         ArgT const& m_arg;
4310         MatcherT m_matcher;
4311         StringRef m_matcherString;
4312
4313     public:
4314         MatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString) :
4315             ITransientExpression{true, matcher.match(arg)},
4316             m_arg(arg),
4317             m_matcher(matcher),
4318             m_matcherString(matcherString) {}
4319
4320         void streamReconstructedExpression(std::ostream& os) const override {
4321             auto matcherAsString = m_matcher.toString();
4322             os << Catch::Detail::stringify(m_arg) << ' ';
4323             if (matcherAsString == Detail::unprintableString)
4324                 os << m_matcherString;
4325             else
4326                 os << matcherAsString;
4327         }
4328     };
4329
4330     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
4331
4332     void handleExceptionMatchExpr(AssertionHandler& handler,
4333                                   StringMatcher const& matcher,
4334                                   StringRef const& matcherString);
4335
4336     template <typename ArgT, typename MatcherT>
4337     auto makeMatchExpr(ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString)
4338         -> MatchExpr<ArgT, MatcherT> {
4339         return MatchExpr<ArgT, MatcherT>(arg, matcher, matcherString);
4340     }
4341
4342 } // namespace Catch
4343
4344 ///////////////////////////////////////////////////////////////////////////////
4345 #define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg)                            \
4346     do {                                                                                           \
4347         Catch::AssertionHandler catchAssertionHandler(                                             \
4348             macroName##_catch_sr,                                                                  \
4349             CATCH_INTERNAL_LINEINFO,                                                               \
4350             CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher),                  \
4351             resultDisposition);                                                                    \
4352         INTERNAL_CATCH_TRY {                                                                       \
4353             catchAssertionHandler.handleExpr(                                                      \
4354                 Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr));                          \
4355         }                                                                                          \
4356         INTERNAL_CATCH_CATCH(catchAssertionHandler)                                                \
4357         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
4358     } while (false)
4359
4360 ///////////////////////////////////////////////////////////////////////////////
4361 #define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...)   \
4362     do {                                                                                           \
4363         Catch::AssertionHandler catchAssertionHandler(                                             \
4364             macroName##_catch_sr,                                                                  \
4365             CATCH_INTERNAL_LINEINFO,                                                               \
4366             CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(                   \
4367                 exceptionType) ","                                                                 \
4368                                " " CATCH_INTERNAL_STRINGIFY(matcher),                              \
4369             resultDisposition);                                                                    \
4370         if (catchAssertionHandler.allowThrows())                                                   \
4371             try {                                                                                  \
4372                 static_cast<void>(__VA_ARGS__);                                                    \
4373                 catchAssertionHandler.handleUnexpectedExceptionNotThrown();                        \
4374             } catch (exceptionType const& ex) {                                                    \
4375                 catchAssertionHandler.handleExpr(                                                  \
4376                     Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr));                       \
4377             } catch (...) {                                                                        \
4378                 catchAssertionHandler.handleUnexpectedInflightException();                         \
4379             }                                                                                      \
4380         else                                                                                       \
4381             catchAssertionHandler.handleThrowingCallSkipped();                                     \
4382         INTERNAL_CATCH_REACT(catchAssertionHandler)                                                \
4383     } while (false)
4384
4385 // end catch_capture_matchers.h
4386 #endif
4387 // start catch_generators.hpp
4388
4389 // start catch_interfaces_generatortracker.h
4390
4391 #include <memory>
4392
4393 namespace Catch {
4394
4395     namespace Generators {
4396         class GeneratorUntypedBase {
4397         public:
4398             GeneratorUntypedBase() = default;
4399             virtual ~GeneratorUntypedBase();
4400             // Attempts to move the generator to the next element
4401             //
4402             // Returns true iff the move succeeded (and a valid element
4403             // can be retrieved).
4404             virtual bool next() = 0;
4405         };
4406         using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
4407
4408     } // namespace Generators
4409
4410     struct IGeneratorTracker {
4411         virtual ~IGeneratorTracker();
4412         virtual auto hasGenerator() const -> bool = 0;
4413         virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
4414         virtual void setGenerator(Generators::GeneratorBasePtr&& generator) = 0;
4415     };
4416
4417 } // namespace Catch
4418
4419 // end catch_interfaces_generatortracker.h
4420 // start catch_enforce.h
4421
4422 #include <exception>
4423
4424 namespace Catch {
4425 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
4426     template <typename Ex> [[noreturn]] void throw_exception(Ex const& e) { throw e; }
4427 #else // ^^ Exceptions are enabled //  Exceptions are disabled vv
4428     [[noreturn]] void throw_exception(std::exception const& e);
4429 #endif
4430
4431     [[noreturn]] void throw_logic_error(std::string const& msg);
4432     [[noreturn]] void throw_domain_error(std::string const& msg);
4433     [[noreturn]] void throw_runtime_error(std::string const& msg);
4434
4435 } // namespace Catch
4436
4437 #define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str()
4438
4439 #define CATCH_INTERNAL_ERROR(...)                                                                  \
4440     Catch::throw_logic_error(                                                                      \
4441         CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
4442
4443 #define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__))
4444
4445 #define CATCH_RUNTIME_ERROR(...) Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__))
4446
4447 #define CATCH_ENFORCE(condition, ...)                                                              \
4448     do {                                                                                           \
4449         if (!(condition))                                                                          \
4450             CATCH_ERROR(__VA_ARGS__);                                                              \
4451     } while (false)
4452
4453 // end catch_enforce.h
4454 #include <memory>
4455 #include <vector>
4456 #include <cassert>
4457
4458 #include <utility>
4459 #include <exception>
4460
4461 namespace Catch {
4462
4463     class GeneratorException : public std::exception {
4464         const char* const m_msg = "";
4465
4466     public:
4467         GeneratorException(const char* msg) : m_msg(msg) {}
4468
4469         const char* what() const noexcept override final;
4470     };
4471
4472     namespace Generators {
4473
4474         // !TBD move this into its own location?
4475         namespace pf {
4476             template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
4477                 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
4478             }
4479         } // namespace pf
4480
4481         template <typename T> struct IGenerator : GeneratorUntypedBase {
4482             virtual ~IGenerator() = default;
4483
4484             // Returns the current element of the generator
4485             //
4486             // \Precondition The generator is either freshly constructed,
4487             // or the last call to `next()` returned true
4488             virtual T const& get() const = 0;
4489             using type = T;
4490         };
4491
4492         template <typename T> class SingleValueGenerator final : public IGenerator<T> {
4493             T m_value;
4494
4495         public:
4496             SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
4497
4498             T const& get() const override { return m_value; }
4499             bool next() override { return false; }
4500         };
4501
4502         template <typename T> class FixedValuesGenerator final : public IGenerator<T> {
4503             static_assert(!std::is_same<T, bool>::value,
4504                           "FixedValuesGenerator does not support bools because "
4505                           "of std::vector<bool>"
4506                           "specialization, use SingleValue Generator instead.");
4507             std::vector<T> m_values;
4508             size_t m_idx = 0;
4509
4510         public:
4511             FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
4512
4513             T const& get() const override { return m_values[m_idx]; }
4514             bool next() override {
4515                 ++m_idx;
4516                 return m_idx < m_values.size();
4517             }
4518         };
4519
4520         template <typename T> class GeneratorWrapper final {
4521             std::unique_ptr<IGenerator<T>> m_generator;
4522
4523         public:
4524             GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator) :
4525                 m_generator(std::move(generator)) {}
4526             T const& get() const { return m_generator->get(); }
4527             bool next() { return m_generator->next(); }
4528         };
4529
4530         template <typename T> GeneratorWrapper<T> value(T&& value) {
4531             return GeneratorWrapper<T>(
4532                 pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4533         }
4534         template <typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) {
4535             return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4536         }
4537
4538         template <typename T> class Generators : public IGenerator<T> {
4539             std::vector<GeneratorWrapper<T>> m_generators;
4540             size_t m_current = 0;
4541
4542             void populate(GeneratorWrapper<T>&& generator) {
4543                 m_generators.emplace_back(std::move(generator));
4544             }
4545             void populate(T&& val) { m_generators.emplace_back(value(std::forward<T>(val))); }
4546             template <typename U> void populate(U&& val) { populate(T(std::forward<U>(val))); }
4547             template <typename U, typename... Gs>
4548             void populate(U&& valueOrGenerator, Gs&&... moreGenerators) {
4549                 populate(std::forward<U>(valueOrGenerator));
4550                 populate(std::forward<Gs>(moreGenerators)...);
4551             }
4552
4553         public:
4554             template <typename... Gs> Generators(Gs&&... moreGenerators) {
4555                 m_generators.reserve(sizeof...(Gs));
4556                 populate(std::forward<Gs>(moreGenerators)...);
4557             }
4558
4559             T const& get() const override { return m_generators[m_current].get(); }
4560
4561             bool next() override {
4562                 if (m_current >= m_generators.size()) {
4563                     return false;
4564                 }
4565                 const bool current_status = m_generators[m_current].next();
4566                 if (!current_status) {
4567                     ++m_current;
4568                 }
4569                 return m_current < m_generators.size();
4570             }
4571         };
4572
4573         template <typename... Ts>
4574         GeneratorWrapper<std::tuple<Ts...>>
4575         table(std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples) {
4576             return values<std::tuple<Ts...>>(tuples);
4577         }
4578
4579         // Tag type to signal that a generator sequence should convert arguments
4580         // to a specific type
4581         template <typename T> struct as {};
4582
4583         template <typename T, typename... Gs>
4584         auto makeGenerators(GeneratorWrapper<T>&& generator, Gs&&... moreGenerators)
4585             -> Generators<T> {
4586             return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4587         }
4588         template <typename T>
4589         auto makeGenerators(GeneratorWrapper<T>&& generator) -> Generators<T> {
4590             return Generators<T>(std::move(generator));
4591         }
4592         template <typename T, typename... Gs>
4593         auto makeGenerators(T&& val, Gs&&... moreGenerators) -> Generators<T> {
4594             return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
4595         }
4596         template <typename T, typename U, typename... Gs>
4597         auto makeGenerators(as<T>, U&& val, Gs&&... moreGenerators) -> Generators<T> {
4598             return makeGenerators(value(T(std::forward<U>(val))),
4599                                   std::forward<Gs>(moreGenerators)...);
4600         }
4601
4602         auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
4603             -> IGeneratorTracker&;
4604
4605         template <typename L>
4606         // Note: The type after -> is weird, because VS2015 cannot parse
4607         //       the expression used in the typedef inside, when it is in
4608         //       return type. Yeah.
4609         auto generate(StringRef generatorName,
4610                       SourceLineInfo const& lineInfo,
4611                       L const& generatorExpression)
4612             -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4613             using UnderlyingType = typename decltype(generatorExpression())::type;
4614
4615             IGeneratorTracker& tracker = acquireGeneratorTracker(generatorName, lineInfo);
4616             if (!tracker.hasGenerator()) {
4617                 tracker.setGenerator(
4618                     pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4619             }
4620
4621             auto const& generator =
4622                 static_cast<IGenerator<UnderlyingType> const&>(*tracker.getGenerator());
4623             return generator.get();
4624         }
4625
4626     } // namespace Generators
4627 } // namespace Catch
4628
4629 #define GENERATE(...)                                                                              \
4630     Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)),   \
4631                                 CATCH_INTERNAL_LINEINFO,                                           \
4632                                 [] {                                                               \
4633                                     using namespace Catch::Generators;                             \
4634                                     return makeGenerators(__VA_ARGS__);                            \
4635                                 }) // NOLINT(google-build-using-namespace)
4636 #define GENERATE_COPY(...)                                                                         \
4637     Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)),   \
4638                                 CATCH_INTERNAL_LINEINFO,                                           \
4639                                 [=] {                                                              \
4640                                     using namespace Catch::Generators;                             \
4641                                     return makeGenerators(__VA_ARGS__);                            \
4642                                 }) // NOLINT(google-build-using-namespace)
4643 #define GENERATE_REF(...)                                                                          \
4644     Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)),   \
4645                                 CATCH_INTERNAL_LINEINFO,                                           \
4646                                 [&] {                                                              \
4647                                     using namespace Catch::Generators;                             \
4648                                     return makeGenerators(__VA_ARGS__);                            \
4649                                 }) // NOLINT(google-build-using-namespace)
4650
4651 // end catch_generators.hpp
4652 // start catch_generators_generic.hpp
4653
4654 namespace Catch {
4655     namespace Generators {
4656
4657         template <typename T> class TakeGenerator : public IGenerator<T> {
4658             GeneratorWrapper<T> m_generator;
4659             size_t m_returned = 0;
4660             size_t m_target;
4661
4662         public:
4663             TakeGenerator(size_t target, GeneratorWrapper<T>&& generator) :
4664                 m_generator(std::move(generator)), m_target(target) {
4665                 assert(target != 0 && "Empty generators are not allowed");
4666             }
4667             T const& get() const override { return m_generator.get(); }
4668             bool next() override {
4669                 ++m_returned;
4670                 if (m_returned >= m_target) {
4671                     return false;
4672                 }
4673
4674                 const auto success = m_generator.next();
4675                 // If the underlying generator does not contain enough values
4676                 // then we cut short as well
4677                 if (!success) {
4678                     m_returned = m_target;
4679                 }
4680                 return success;
4681             }
4682         };
4683
4684         template <typename T>
4685         GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4686             return GeneratorWrapper<T>(
4687                 pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4688         }
4689
4690         template <typename T, typename Predicate> class FilterGenerator : public IGenerator<T> {
4691             GeneratorWrapper<T> m_generator;
4692             Predicate m_predicate;
4693
4694         public:
4695             template <typename P = Predicate>
4696             FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator) :
4697                 m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) {
4698                 if (!m_predicate(m_generator.get())) {
4699                     // It might happen that there are no values that pass the
4700                     // filter. In that case we throw an exception.
4701                     auto has_initial_value = next();
4702                     if (!has_initial_value) {
4703                         Catch::throw_exception(
4704                             GeneratorException("No valid value found in filtered generator"));
4705                     }
4706                 }
4707             }
4708
4709             T const& get() const override { return m_generator.get(); }
4710
4711             bool next() override {
4712                 bool success = m_generator.next();
4713                 if (!success) {
4714                     return false;
4715                 }
4716                 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true)
4717                     ;
4718                 return success;
4719             }
4720         };
4721
4722         template <typename T, typename Predicate>
4723         GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4724             return GeneratorWrapper<T>(
4725                 std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(
4726                     std::forward<Predicate>(pred), std::move(generator))));
4727         }
4728
4729         template <typename T> class RepeatGenerator : public IGenerator<T> {
4730             static_assert(!std::is_same<T, bool>::value,
4731                           "RepeatGenerator currently does not support bools"
4732                           "because of std::vector<bool> specialization");
4733             GeneratorWrapper<T> m_generator;
4734             mutable std::vector<T> m_returned;
4735             size_t m_target_repeats;
4736             size_t m_current_repeat = 0;
4737             size_t m_repeat_index = 0;
4738
4739         public:
4740             RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator) :
4741                 m_generator(std::move(generator)), m_target_repeats(repeats) {
4742                 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4743             }
4744
4745             T const& get() const override {
4746                 if (m_current_repeat == 0) {
4747                     m_returned.push_back(m_generator.get());
4748                     return m_returned.back();
4749                 }
4750                 return m_returned[m_repeat_index];
4751             }
4752
4753             bool next() override {
4754                 // There are 2 basic cases:
4755                 // 1) We are still reading the generator
4756                 // 2) We are reading our own cache
4757
4758                 // In the first case, we need to poke the underlying generator.
4759                 // If it happily moves, we are left in that state, otherwise it
4760                 // is time to start reading from our cache
4761                 if (m_current_repeat == 0) {
4762                     const auto success = m_generator.next();
4763                     if (!success) {
4764                         ++m_current_repeat;
4765                     }
4766                     return m_current_repeat < m_target_repeats;
4767                 }
4768
4769                 // In the second case, we need to move indices forward and check
4770                 // that we haven't run up against the end
4771                 ++m_repeat_index;
4772                 if (m_repeat_index == m_returned.size()) {
4773                     m_repeat_index = 0;
4774                     ++m_current_repeat;
4775                 }
4776                 return m_current_repeat < m_target_repeats;
4777             }
4778         };
4779
4780         template <typename T>
4781         GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4782             return GeneratorWrapper<T>(
4783                 pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4784         }
4785
4786         template <typename T, typename U, typename Func> class MapGenerator : public IGenerator<T> {
4787             // TBD: provide static assert for mapping function, for friendly
4788             // error message
4789             GeneratorWrapper<U> m_generator;
4790             Func m_function;
4791             // To avoid returning dangling reference, we have to save the values
4792             T m_cache;
4793
4794         public:
4795             template <typename F2 = Func>
4796             MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4797                 m_generator(std::move(generator)),
4798                 m_function(std::forward<F2>(function)),
4799                 m_cache(m_function(m_generator.get())) {}
4800
4801             T const& get() const override { return m_cache; }
4802             bool next() override {
4803                 const auto success = m_generator.next();
4804                 if (success) {
4805                     m_cache = m_function(m_generator.get());
4806                 }
4807                 return success;
4808             }
4809         };
4810
4811         template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4812         GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4813             return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4814                 std::forward<Func>(function), std::move(generator)));
4815         }
4816
4817         template <typename T, typename U, typename Func>
4818         GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4819             return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4820                 std::forward<Func>(function), std::move(generator)));
4821         }
4822
4823         template <typename T> class ChunkGenerator final : public IGenerator<std::vector<T>> {
4824             std::vector<T> m_chunk;
4825             size_t m_chunk_size;
4826             GeneratorWrapper<T> m_generator;
4827             bool m_used_up = false;
4828
4829         public:
4830             ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4831                 m_chunk_size(size), m_generator(std::move(generator)) {
4832                 m_chunk.reserve(m_chunk_size);
4833                 if (m_chunk_size != 0) {
4834                     m_chunk.push_back(m_generator.get());
4835                     for (size_t i = 1; i < m_chunk_size; ++i) {
4836                         if (!m_generator.next()) {
4837                             Catch::throw_exception(
4838                                 GeneratorException("Not enough values to initialize the first "
4839                                                    "chunk"));
4840                         }
4841                         m_chunk.push_back(m_generator.get());
4842                     }
4843                 }
4844             }
4845             std::vector<T> const& get() const override { return m_chunk; }
4846             bool next() override {
4847                 m_chunk.clear();
4848                 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4849                     if (!m_generator.next()) {
4850                         return false;
4851                     }
4852                     m_chunk.push_back(m_generator.get());
4853                 }
4854                 return true;
4855             }
4856         };
4857
4858         template <typename T>
4859         GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4860             return GeneratorWrapper<std::vector<T>>(
4861                 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)));
4862         }
4863
4864     } // namespace Generators
4865 } // namespace Catch
4866
4867 // end catch_generators_generic.hpp
4868 // start catch_generators_specific.hpp
4869
4870 // start catch_context.h
4871
4872 #include <memory>
4873
4874 namespace Catch {
4875
4876     struct IResultCapture;
4877     struct IRunner;
4878     struct IConfig;
4879     struct IMutableContext;
4880
4881     using IConfigPtr = std::shared_ptr<IConfig const>;
4882
4883     struct IContext {
4884         virtual ~IContext();
4885
4886         virtual IResultCapture* getResultCapture() = 0;
4887         virtual IRunner* getRunner() = 0;
4888         virtual IConfigPtr const& getConfig() const = 0;
4889     };
4890
4891     struct IMutableContext : IContext {
4892         virtual ~IMutableContext();
4893         virtual void setResultCapture(IResultCapture* resultCapture) = 0;
4894         virtual void setRunner(IRunner* runner) = 0;
4895         virtual void setConfig(IConfigPtr const& config) = 0;
4896
4897     private:
4898         static IMutableContext* currentContext;
4899         friend IMutableContext& getCurrentMutableContext();
4900         friend void cleanUpContext();
4901         static void createContext();
4902     };
4903
4904     inline IMutableContext& getCurrentMutableContext() {
4905         if (!IMutableContext::currentContext)
4906             IMutableContext::createContext();
4907         // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4908         return *IMutableContext::currentContext;
4909     }
4910
4911     inline IContext& getCurrentContext() { return getCurrentMutableContext(); }
4912
4913     void cleanUpContext();
4914
4915     class SimplePcg32;
4916     SimplePcg32& rng();
4917 } // namespace Catch
4918
4919 // end catch_context.h
4920 // start catch_interfaces_config.h
4921
4922 // start catch_option.hpp
4923
4924 namespace Catch {
4925
4926     // An optional type
4927     template <typename T> class Option {
4928     public:
4929         Option() : nullableValue(nullptr) {}
4930         Option(T const& _value) : nullableValue(new (storage) T(_value)) {}
4931         Option(Option const& _other) : nullableValue(_other ? new (storage) T(*_other) : nullptr) {}
4932
4933         ~Option() { reset(); }
4934
4935         Option& operator=(Option const& _other) {
4936             if (&_other != this) {
4937                 reset();
4938                 if (_other)
4939                     nullableValue = new (storage) T(*_other);
4940             }
4941             return *this;
4942         }
4943         Option& operator=(T const& _value) {
4944             reset();
4945             nullableValue = new (storage) T(_value);
4946             return *this;
4947         }
4948
4949         void reset() {
4950             if (nullableValue)
4951                 nullableValue->~T();
4952             nullableValue = nullptr;
4953         }
4954
4955         T& operator*() { return *nullableValue; }
4956         T const& operator*() const { return *nullableValue; }
4957         T* operator->() { return nullableValue; }
4958         const T* operator->() const { return nullableValue; }
4959
4960         T valueOr(T const& defaultValue) const {
4961             return nullableValue ? *nullableValue : defaultValue;
4962         }
4963
4964         bool some() const { return nullableValue != nullptr; }
4965         bool none() const { return nullableValue == nullptr; }
4966
4967         bool operator!() const { return nullableValue == nullptr; }
4968         explicit operator bool() const { return some(); }
4969
4970     private:
4971         T* nullableValue;
4972         alignas(alignof(T)) char storage[sizeof(T)];
4973     };
4974
4975 } // end namespace Catch
4976
4977 // end catch_option.hpp
4978 #include <chrono>
4979 #include <iosfwd>
4980 #include <string>
4981 #include <vector>
4982 #include <memory>
4983
4984 namespace Catch {
4985
4986     enum class Verbosity { Quiet = 0, Normal, High };
4987
4988     struct WarnAbout {
4989         enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 };
4990     };
4991
4992     struct ShowDurations {
4993         enum OrNot { DefaultForReporter, Always, Never };
4994     };
4995     struct RunTests {
4996         enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder };
4997     };
4998     struct UseColour {
4999         enum YesOrNo { Auto, Yes, No };
5000     };
5001     struct WaitForKeypress {
5002         enum When {
5003             Never,
5004             BeforeStart = 1,
5005             BeforeExit = 2,
5006             BeforeStartAndExit = BeforeStart | BeforeExit
5007         };
5008     };
5009
5010     class TestSpec;
5011
5012     struct IConfig : NonCopyable {
5013
5014         virtual ~IConfig();
5015
5016         virtual bool allowThrows() const = 0;
5017         virtual std::ostream& stream() const = 0;
5018         virtual std::string name() const = 0;
5019         virtual bool includeSuccessfulResults() const = 0;
5020         virtual bool shouldDebugBreak() const = 0;
5021         virtual bool warnAboutMissingAssertions() const = 0;
5022         virtual bool warnAboutNoTests() const = 0;
5023         virtual int abortAfter() const = 0;
5024         virtual bool showInvisibles() const = 0;
5025         virtual ShowDurations::OrNot showDurations() const = 0;
5026         virtual double minDuration() const = 0;
5027         virtual TestSpec const& testSpec() const = 0;
5028         virtual bool hasTestFilters() const = 0;
5029         virtual std::vector<std::string> const& getTestsOrTags() const = 0;
5030         virtual RunTests::InWhatOrder runOrder() const = 0;
5031         virtual unsigned int rngSeed() const = 0;
5032         virtual UseColour::YesOrNo useColour() const = 0;
5033         virtual std::vector<std::string> const& getSectionsToRun() const = 0;
5034         virtual Verbosity verbosity() const = 0;
5035
5036         virtual bool benchmarkNoAnalysis() const = 0;
5037         virtual int benchmarkSamples() const = 0;
5038         virtual double benchmarkConfidenceInterval() const = 0;
5039         virtual unsigned int benchmarkResamples() const = 0;
5040         virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
5041     };
5042
5043     using IConfigPtr = std::shared_ptr<IConfig const>;
5044 } // namespace Catch
5045
5046 // end catch_interfaces_config.h
5047 // start catch_random_number_generator.h
5048
5049 #include <cstdint>
5050
5051 namespace Catch {
5052
5053     // This is a simple implementation of C++11 Uniform Random Number
5054     // Generator. It does not provide all operators, because Catch2
5055     // does not use it, but it should behave as expected inside stdlib's
5056     // distributions.
5057     // The implementation is based on the PCG family (http://pcg-random.org)
5058     class SimplePcg32 {
5059         using state_type = std::uint64_t;
5060
5061     public:
5062         using result_type = std::uint32_t;
5063         static constexpr result_type(min)() { return 0; }
5064         static constexpr result_type(max)() { return static_cast<result_type>(-1); }
5065
5066         // Provide some default initial state for the default constructor
5067         SimplePcg32() : SimplePcg32(0xed743cc4U) {}
5068
5069         explicit SimplePcg32(result_type seed_);
5070
5071         void seed(result_type seed_);
5072         void discard(uint64_t skip);
5073
5074         result_type operator()();
5075
5076     private:
5077         friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
5078         friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
5079
5080         // In theory we also need operator<< and operator>>
5081         // In practice we do not use them, so we will skip them for now
5082
5083         std::uint64_t m_state;
5084         // This part of the state determines which "stream" of the numbers
5085         // is chosen -- we take it as a constant for Catch2, so we only
5086         // need to deal with seeding the main state.
5087         // Picked by reading 8 bytes from `/dev/random` :-)
5088         static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
5089     };
5090
5091 } // end namespace Catch
5092
5093 // end catch_random_number_generator.h
5094 #include <random>
5095
5096 namespace Catch {
5097     namespace Generators {
5098
5099         template <typename Float> class RandomFloatingGenerator final : public IGenerator<Float> {
5100             Catch::SimplePcg32& m_rng;
5101             std::uniform_real_distribution<Float> m_dist;
5102             Float m_current_number;
5103
5104         public:
5105             RandomFloatingGenerator(Float a, Float b) : m_rng(rng()), m_dist(a, b) {
5106                 static_cast<void>(next());
5107             }
5108
5109             Float const& get() const override { return m_current_number; }
5110             bool next() override {
5111                 m_current_number = m_dist(m_rng);
5112                 return true;
5113             }
5114         };
5115
5116         template <typename Integer>
5117         class RandomIntegerGenerator final : public IGenerator<Integer> {
5118             Catch::SimplePcg32& m_rng;
5119             std::uniform_int_distribution<Integer> m_dist;
5120             Integer m_current_number;
5121
5122         public:
5123             RandomIntegerGenerator(Integer a, Integer b) : m_rng(rng()), m_dist(a, b) {
5124                 static_cast<void>(next());
5125             }
5126
5127             Integer const& get() const override { return m_current_number; }
5128             bool next() override {
5129                 m_current_number = m_dist(m_rng);
5130                 return true;
5131             }
5132         };
5133
5134         // TODO: Ideally this would be also constrained against the various char
5135         // types,
5136         //       but I don't expect users to run into that in practice.
5137         template <typename T>
5138         typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
5139                                 GeneratorWrapper<T>>::type
5140         random(T a, T b) {
5141             return GeneratorWrapper<T>(pf::make_unique<RandomIntegerGenerator<T>>(a, b));
5142         }
5143
5144         template <typename T>
5145         typename std::enable_if<std::is_floating_point<T>::value, GeneratorWrapper<T>>::type
5146         random(T a, T b) {
5147             return GeneratorWrapper<T>(pf::make_unique<RandomFloatingGenerator<T>>(a, b));
5148         }
5149
5150         template <typename T> class RangeGenerator final : public IGenerator<T> {
5151             T m_current;
5152             T m_end;
5153             T m_step;
5154             bool m_positive;
5155
5156         public:
5157             RangeGenerator(T const& start, T const& end, T const& step) :
5158                 m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) {
5159                 assert(m_current != m_end && "Range start and end cannot be equal");
5160                 assert(m_step != T(0) && "Step size cannot be zero");
5161                 assert(
5162                     ((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
5163                     "Step moves away from end");
5164             }
5165
5166             RangeGenerator(T const& start, T const& end) :
5167                 RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {}
5168
5169             T const& get() const override { return m_current; }
5170
5171             bool next() override {
5172                 m_current += m_step;
5173                 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
5174             }
5175         };
5176
5177         template <typename T>
5178         GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
5179             static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
5180                           "Type must be numeric");
5181             return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
5182         }
5183
5184         template <typename T> GeneratorWrapper<T> range(T const& start, T const& end) {
5185             static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
5186                           "Type must be an integer");
5187             return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
5188         }
5189
5190         template <typename T> class IteratorGenerator final : public IGenerator<T> {
5191             static_assert(!std::is_same<T, bool>::value,
5192                           "IteratorGenerator currently does not support bools"
5193                           "because of std::vector<bool> specialization");
5194
5195             std::vector<T> m_elems;
5196             size_t m_current = 0;
5197
5198         public:
5199             template <typename InputIterator, typename InputSentinel>
5200             IteratorGenerator(InputIterator first, InputSentinel last) : m_elems(first, last) {
5201                 if (m_elems.empty()) {
5202                     Catch::throw_exception(
5203                         GeneratorException("IteratorGenerator received no valid values"));
5204                 }
5205             }
5206
5207             T const& get() const override { return m_elems[m_current]; }
5208
5209             bool next() override {
5210                 ++m_current;
5211                 return m_current != m_elems.size();
5212             }
5213         };
5214
5215         template <typename InputIterator,
5216                   typename InputSentinel,
5217                   typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
5218         GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
5219             return GeneratorWrapper<ResultType>(
5220                 pf::make_unique<IteratorGenerator<ResultType>>(from, to));
5221         }
5222
5223         template <typename Container, typename ResultType = typename Container::value_type>
5224         GeneratorWrapper<ResultType> from_range(Container const& cnt) {
5225             return GeneratorWrapper<ResultType>(
5226                 pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
5227         }
5228
5229     } // namespace Generators
5230 } // namespace Catch
5231
5232 // end catch_generators_specific.hpp
5233
5234 // These files are included here so the single_include script doesn't put them
5235 // in the conditionally compiled sections
5236 // start catch_test_case_info.h
5237
5238 #include <string>
5239 #include <vector>
5240 #include <memory>
5241
5242 #ifdef __clang__
5243 #pragma clang diagnostic push
5244 #pragma clang diagnostic ignored "-Wpadded"
5245 #endif
5246
5247 namespace Catch {
5248
5249     struct ITestInvoker;
5250
5251     struct TestCaseInfo {
5252         enum SpecialProperties {
5253             None = 0,
5254             IsHidden = 1 << 1,
5255             ShouldFail = 1 << 2,
5256             MayFail = 1 << 3,
5257             Throws = 1 << 4,
5258             NonPortable = 1 << 5,
5259             Benchmark = 1 << 6
5260         };
5261
5262         TestCaseInfo(std::string const& _name,
5263                      std::string const& _className,
5264                      std::string const& _description,
5265                      std::vector<std::string> const& _tags,
5266                      SourceLineInfo const& _lineInfo);
5267
5268         friend void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags);
5269
5270         bool isHidden() const;
5271         bool throws() const;
5272         bool okToFail() const;
5273         bool expectedToFail() const;
5274
5275         std::string tagsAsString() const;
5276
5277         std::string name;
5278         std::string className;
5279         std::string description;
5280         std::vector<std::string> tags;
5281         std::vector<std::string> lcaseTags;
5282         SourceLineInfo lineInfo;
5283         SpecialProperties properties;
5284     };
5285
5286     class TestCase : public TestCaseInfo {
5287     public:
5288         TestCase(ITestInvoker* testCase, TestCaseInfo&& info);
5289
5290         TestCase withName(std::string const& _newName) const;
5291
5292         void invoke() const;
5293
5294         TestCaseInfo const& getTestCaseInfo() const;
5295
5296         bool operator==(TestCase const& other) const;
5297         bool operator<(TestCase const& other) const;
5298
5299     private:
5300         std::shared_ptr<ITestInvoker> test;
5301     };
5302
5303     TestCase makeTestCase(ITestInvoker* testCase,
5304                           std::string const& className,
5305                           NameAndTags const& nameAndTags,
5306                           SourceLineInfo const& lineInfo);
5307 } // namespace Catch
5308
5309 #ifdef __clang__
5310 #pragma clang diagnostic pop
5311 #endif
5312
5313 // end catch_test_case_info.h
5314 // start catch_interfaces_runner.h
5315
5316 namespace Catch {
5317
5318     struct IRunner {
5319         virtual ~IRunner();
5320         virtual bool aborting() const = 0;
5321     };
5322 } // namespace Catch
5323
5324 // end catch_interfaces_runner.h
5325
5326 #ifdef __OBJC__
5327 // start catch_objc.hpp
5328
5329 #import <objc/runtime.h>
5330
5331 #include <string>
5332
5333 // NB. Any general catch headers included here must be included
5334 // in catch.hpp first to make sure they are included by the single
5335 // header for non obj-usage
5336
5337 ///////////////////////////////////////////////////////////////////////////////
5338 // This protocol is really only here for (self) documenting purposes, since
5339 // all its methods are optional.
5340 @protocol OcFixture
5341
5342 @optional
5343
5344 - (void)setUp;
5345 - (void)tearDown;
5346
5347 @end
5348
5349 namespace Catch {
5350
5351     class OcMethod : public ITestInvoker {
5352
5353     public:
5354         OcMethod(Class cls, SEL sel) : m_cls(cls), m_sel(sel) {}
5355
5356         virtual void invoke() const {
5357             id obj = [[m_cls alloc] init];
5358
5359             performOptionalSelector(obj, @selector(setUp));
5360             performOptionalSelector(obj, m_sel);
5361             performOptionalSelector(obj, @selector(tearDown));
5362
5363             arcSafeRelease(obj);
5364         }
5365
5366     private:
5367         virtual ~OcMethod() {}
5368
5369         Class m_cls;
5370         SEL m_sel;
5371     };
5372
5373     namespace Detail {
5374
5375         inline std::string getAnnotation(Class cls,
5376                                          std::string const& annotationName,
5377                                          std::string const& testCaseName) {
5378             NSString* selStr = [[NSString alloc]
5379                 initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
5380             SEL sel = NSSelectorFromString(selStr);
5381             arcSafeRelease(selStr);
5382             id value = performOptionalSelector(cls, sel);
5383             if (value)
5384                 return [(NSString*)value UTF8String];
5385             return "";
5386         }
5387     } // namespace Detail
5388
5389     inline std::size_t registerTestMethods() {
5390         std::size_t noTestMethods = 0;
5391         int noClasses = objc_getClassList(nullptr, 0);
5392
5393         Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc(sizeof(Class) * noClasses);
5394         objc_getClassList(classes, noClasses);
5395
5396         for (int c = 0; c < noClasses; c++) {
5397             Class cls = classes[c];
5398             {
5399                 u_int count;
5400                 Method* methods = class_copyMethodList(cls, &count);
5401                 for (u_int m = 0; m < count; m++) {
5402                     SEL selector = method_getName(methods[m]);
5403                     std::string methodName = sel_getName(selector);
5404                     if (startsWith(methodName, "Catch_TestCase_")) {
5405                         std::string testCaseName = methodName.substr(15);
5406                         std::string name = Detail::getAnnotation(cls, "Name", testCaseName);
5407                         std::string desc = Detail::getAnnotation(cls, "Description", testCaseName);
5408                         const char* className = class_getName(cls);
5409
5410                         getMutableRegistryHub().registerTest(
5411                             makeTestCase(new OcMethod(cls, selector),
5412                                          className,
5413                                          NameAndTags(name.c_str(), desc.c_str()),
5414                                          SourceLineInfo("", 0)));
5415                         noTestMethods++;
5416                     }
5417                 }
5418                 free(methods);
5419             }
5420         }
5421         return noTestMethods;
5422     }
5423
5424 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
5425
5426     namespace Matchers {
5427         namespace Impl {
5428             namespace NSStringMatchers {
5429
5430                 struct StringHolder : MatcherBase<NSString*> {
5431                     StringHolder(NSString* substr) : m_substr([substr copy]) {}
5432                     StringHolder(StringHolder const& other) : m_substr([other.m_substr copy]) {}
5433                     StringHolder() { arcSafeRelease(m_substr); }
5434
5435                     bool match(NSString* str) const override { return false; }
5436
5437                     NSString* CATCH_ARC_STRONG m_substr;
5438                 };
5439
5440                 struct Equals : StringHolder {
5441                     Equals(NSString* substr) : StringHolder(substr) {}
5442
5443                     bool match(NSString* str) const override {
5444                         return (str != nil || m_substr == nil) && [str isEqualToString:m_substr];
5445                     }
5446
5447                     std::string describe() const override {
5448                         return "equals string: " + Catch::Detail::stringify(m_substr);
5449                     }
5450                 };
5451
5452                 struct Contains : StringHolder {
5453                     Contains(NSString* substr) : StringHolder(substr) {}
5454
5455                     bool match(NSString* str) const override {
5456                         return (str != nil || m_substr == nil) &&
5457                                [str rangeOfString:m_substr].location != NSNotFound;
5458                     }
5459
5460                     std::string describe() const override {
5461                         return "contains string: " + Catch::Detail::stringify(m_substr);
5462                     }
5463                 };
5464
5465                 struct StartsWith : StringHolder {
5466                     StartsWith(NSString* substr) : StringHolder(substr) {}
5467
5468                     bool match(NSString* str) const override {
5469                         return (str != nil || m_substr == nil) &&
5470                                [str rangeOfString:m_substr].location == 0;
5471                     }
5472
5473                     std::string describe() const override {
5474                         return "starts with: " + Catch::Detail::stringify(m_substr);
5475                     }
5476                 };
5477                 struct EndsWith : StringHolder {
5478                     EndsWith(NSString* substr) : StringHolder(substr) {}
5479
5480                     bool match(NSString* str) const override {
5481                         return (str != nil || m_substr == nil) &&
5482                                [str rangeOfString:m_substr].location ==
5483                                    [str length] - [m_substr length];
5484                     }
5485
5486                     std::string describe() const override {
5487                         return "ends with: " + Catch::Detail::stringify(m_substr);
5488                     }
5489                 };
5490
5491             } // namespace NSStringMatchers
5492         }     // namespace Impl
5493
5494         inline Impl::NSStringMatchers::Equals Equals(NSString* substr) {
5495             return Impl::NSStringMatchers::Equals(substr);
5496         }
5497
5498         inline Impl::NSStringMatchers::Contains Contains(NSString* substr) {
5499             return Impl::NSStringMatchers::Contains(substr);
5500         }
5501
5502         inline Impl::NSStringMatchers::StartsWith StartsWith(NSString* substr) {
5503             return Impl::NSStringMatchers::StartsWith(substr);
5504         }
5505
5506         inline Impl::NSStringMatchers::EndsWith EndsWith(NSString* substr) {
5507             return Impl::NSStringMatchers::EndsWith(substr);
5508         }
5509
5510     } // namespace Matchers
5511
5512     using namespace Matchers;
5513
5514 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5515
5516 } // namespace Catch
5517
5518 ///////////////////////////////////////////////////////////////////////////////
5519 #define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix
5520 #define OC_TEST_CASE2(name, desc, uniqueSuffix)                                                    \
5521     +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) {                              \
5522         return @name;                                                                              \
5523     }                                                                                              \
5524     +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) {                       \
5525         return @desc;                                                                              \
5526     }                                                                                              \
5527     -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix)
5528
5529 #define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__)
5530
5531 // end catch_objc.hpp
5532 #endif
5533
5534 // Benchmarking needs the externally-facing parts of reporters to work
5535 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5536 // start catch_external_interfaces.h
5537
5538 // start catch_reporter_bases.hpp
5539
5540 // start catch_interfaces_reporter.h
5541
5542 // start catch_config.hpp
5543
5544 // start catch_test_spec_parser.h
5545
5546 #ifdef __clang__
5547 #pragma clang diagnostic push
5548 #pragma clang diagnostic ignored "-Wpadded"
5549 #endif
5550
5551 // start catch_test_spec.h
5552
5553 #ifdef __clang__
5554 #pragma clang diagnostic push
5555 #pragma clang diagnostic ignored "-Wpadded"
5556 #endif
5557
5558 // start catch_wildcard_pattern.h
5559
5560 namespace Catch {
5561     class WildcardPattern {
5562         enum WildcardPosition {
5563             NoWildcard = 0,
5564             WildcardAtStart = 1,
5565             WildcardAtEnd = 2,
5566             WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5567         };
5568
5569     public:
5570         WildcardPattern(std::string const& pattern, CaseSensitive::Choice caseSensitivity);
5571         virtual ~WildcardPattern() = default;
5572         virtual bool matches(std::string const& str) const;
5573
5574     private:
5575         std::string normaliseString(std::string const& str) const;
5576         CaseSensitive::Choice m_caseSensitivity;
5577         WildcardPosition m_wildcard = NoWildcard;
5578         std::string m_pattern;
5579     };
5580 } // namespace Catch
5581
5582 // end catch_wildcard_pattern.h
5583 #include <string>
5584 #include <vector>
5585 #include <memory>
5586
5587 namespace Catch {
5588
5589     struct IConfig;
5590
5591     class TestSpec {
5592         class Pattern {
5593         public:
5594             explicit Pattern(std::string const& name);
5595             virtual ~Pattern();
5596             virtual bool matches(TestCaseInfo const& testCase) const = 0;
5597             std::string const& name() const;
5598
5599         private:
5600             std::string const m_name;
5601         };
5602         using PatternPtr = std::shared_ptr<Pattern>;
5603
5604         class NamePattern : public Pattern {
5605         public:
5606             explicit NamePattern(std::string const& name, std::string const& filterString);
5607             bool matches(TestCaseInfo const& testCase) const override;
5608
5609         private:
5610             WildcardPattern m_wildcardPattern;
5611         };
5612
5613         class TagPattern : public Pattern {
5614         public:
5615             explicit TagPattern(std::string const& tag, std::string const& filterString);
5616             bool matches(TestCaseInfo const& testCase) const override;
5617
5618         private:
5619             std::string m_tag;
5620         };
5621
5622         class ExcludedPattern : public Pattern {
5623         public:
5624             explicit ExcludedPattern(PatternPtr const& underlyingPattern);
5625             bool matches(TestCaseInfo const& testCase) const override;
5626
5627         private:
5628             PatternPtr m_underlyingPattern;
5629         };
5630
5631         struct Filter {
5632             std::vector<PatternPtr> m_patterns;
5633
5634             bool matches(TestCaseInfo const& testCase) const;
5635             std::string name() const;
5636         };
5637
5638     public:
5639         struct FilterMatch {
5640             std::string name;
5641             std::vector<TestCase const*> tests;
5642         };
5643         using Matches = std::vector<FilterMatch>;
5644         using vectorStrings = std::vector<std::string>;
5645
5646         bool hasFilters() const;
5647         bool matches(TestCaseInfo const& testCase) const;
5648         Matches matchesByFilter(std::vector<TestCase> const& testCases,
5649                                 IConfig const& config) const;
5650         const vectorStrings& getInvalidArgs() const;
5651
5652     private:
5653         std::vector<Filter> m_filters;
5654         std::vector<std::string> m_invalidArgs;
5655         friend class TestSpecParser;
5656     };
5657 } // namespace Catch
5658
5659 #ifdef __clang__
5660 #pragma clang diagnostic pop
5661 #endif
5662
5663 // end catch_test_spec.h
5664 // start catch_interfaces_tag_alias_registry.h
5665
5666 #include <string>
5667
5668 namespace Catch {
5669
5670     struct TagAlias;
5671
5672     struct ITagAliasRegistry {
5673         virtual ~ITagAliasRegistry();
5674         // Nullptr if not present
5675         virtual TagAlias const* find(std::string const& alias) const = 0;
5676         virtual std::string expandAliases(std::string const& unexpandedTestSpec) const = 0;
5677
5678         static ITagAliasRegistry const& get();
5679     };
5680
5681 } // end namespace Catch
5682
5683 // end catch_interfaces_tag_alias_registry.h
5684 namespace Catch {
5685
5686     class TestSpecParser {
5687         enum Mode { None, Name, QuotedName, Tag, EscapedName };
5688         Mode m_mode = None;
5689         Mode lastMode = None;
5690         bool m_exclusion = false;
5691         std::size_t m_pos = 0;
5692         std::size_t m_realPatternPos = 0;
5693         std::string m_arg;
5694         std::string m_substring;
5695         std::string m_patternName;
5696         std::vector<std::size_t> m_escapeChars;
5697         TestSpec::Filter m_currentFilter;
5698         TestSpec m_testSpec;
5699         ITagAliasRegistry const* m_tagAliases = nullptr;
5700
5701     public:
5702         TestSpecParser(ITagAliasRegistry const& tagAliases);
5703
5704         TestSpecParser& parse(std::string const& arg);
5705         TestSpec testSpec();
5706
5707     private:
5708         bool visitChar(char c);
5709         void startNewMode(Mode mode);
5710         bool processNoneChar(char c);
5711         void processNameChar(char c);
5712         bool processOtherChar(char c);
5713         void endMode();
5714         void escape();
5715         bool isControlChar(char c) const;
5716         void saveLastMode();
5717         void revertBackToLastMode();
5718         void addFilter();
5719         bool separate();
5720
5721         // Handles common preprocessing of the pattern for name/tag patterns
5722         std::string preprocessPattern();
5723         // Adds the current pattern as a test name
5724         void addNamePattern();
5725         // Adds the current pattern as a tag
5726         void addTagPattern();
5727
5728         inline void addCharToPattern(char c) {
5729             m_substring += c;
5730             m_patternName += c;
5731             m_realPatternPos++;
5732         }
5733     };
5734     TestSpec parseTestSpec(std::string const& arg);
5735
5736 } // namespace Catch
5737
5738 #ifdef __clang__
5739 #pragma clang diagnostic pop
5740 #endif
5741
5742 // end catch_test_spec_parser.h
5743 // Libstdc++ doesn't like incomplete classes for unique_ptr
5744
5745 #include <memory>
5746 #include <vector>
5747 #include <string>
5748
5749 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5750 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5751 #endif
5752
5753 namespace Catch {
5754
5755     struct IStream;
5756
5757     struct ConfigData {
5758         bool listTests = false;
5759         bool listTags = false;
5760         bool listReporters = false;
5761         bool listTestNamesOnly = false;
5762
5763         bool showSuccessfulTests = false;
5764         bool shouldDebugBreak = false;
5765         bool noThrow = false;
5766         bool showHelp = false;
5767         bool showInvisibles = false;
5768         bool filenamesAsTags = false;
5769         bool libIdentify = false;
5770
5771         int abortAfter = -1;
5772         unsigned int rngSeed = 0;
5773
5774         bool benchmarkNoAnalysis = false;
5775         unsigned int benchmarkSamples = 100;
5776         double benchmarkConfidenceInterval = 0.95;
5777         unsigned int benchmarkResamples = 100000;
5778         std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5779
5780         Verbosity verbosity = Verbosity::Normal;
5781         WarnAbout::What warnings = WarnAbout::Nothing;
5782         ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5783         double minDuration = -1;
5784         RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5785         UseColour::YesOrNo useColour = UseColour::Auto;
5786         WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5787
5788         std::string outputFilename;
5789         std::string name;
5790         std::string processName;
5791 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5792 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5793 #endif
5794         std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5795 #undef CATCH_CONFIG_DEFAULT_REPORTER
5796
5797         std::vector<std::string> testsOrTags;
5798         std::vector<std::string> sectionsToRun;
5799     };
5800
5801     class Config : public IConfig {
5802     public:
5803         Config() = default;
5804         Config(ConfigData const& data);
5805         virtual ~Config() = default;
5806
5807         std::string const& getFilename() const;
5808
5809         bool listTests() const;
5810         bool listTestNamesOnly() const;
5811         bool listTags() const;
5812         bool listReporters() const;
5813
5814         std::string getProcessName() const;
5815         std::string const& getReporterName() const;
5816
5817         std::vector<std::string> const& getTestsOrTags() const override;
5818         std::vector<std::string> const& getSectionsToRun() const override;
5819
5820         TestSpec const& testSpec() const override;
5821         bool hasTestFilters() const override;
5822
5823         bool showHelp() const;
5824
5825         // IConfig interface
5826         bool allowThrows() const override;
5827         std::ostream& stream() const override;
5828         std::string name() const override;
5829         bool includeSuccessfulResults() const override;
5830         bool warnAboutMissingAssertions() const override;
5831         bool warnAboutNoTests() const override;
5832         ShowDurations::OrNot showDurations() const override;
5833         double minDuration() const override;
5834         RunTests::InWhatOrder runOrder() const override;
5835         unsigned int rngSeed() const override;
5836         UseColour::YesOrNo useColour() const override;
5837         bool shouldDebugBreak() const override;
5838         int abortAfter() const override;
5839         bool showInvisibles() const override;
5840         Verbosity verbosity() const override;
5841         bool benchmarkNoAnalysis() const override;
5842         int benchmarkSamples() const override;
5843         double benchmarkConfidenceInterval() const override;
5844         unsigned int benchmarkResamples() const override;
5845         std::chrono::milliseconds benchmarkWarmupTime() const override;
5846
5847     private:
5848         IStream const* openStream();
5849         ConfigData m_data;
5850
5851         std::unique_ptr<IStream const> m_stream;
5852         TestSpec m_testSpec;
5853         bool m_hasTestFilters = false;
5854     };
5855
5856 } // end namespace Catch
5857
5858 // end catch_config.hpp
5859 // start catch_assertionresult.h
5860
5861 #include <string>
5862
5863 namespace Catch {
5864
5865     struct AssertionResultData {
5866         AssertionResultData() = delete;
5867
5868         AssertionResultData(ResultWas::OfType _resultType, LazyExpression const& _lazyExpression);
5869
5870         std::string message;
5871         mutable std::string reconstructedExpression;
5872         LazyExpression lazyExpression;
5873         ResultWas::OfType resultType;
5874
5875         std::string reconstructExpression() const;
5876     };
5877
5878     class AssertionResult {
5879     public:
5880         AssertionResult() = delete;
5881         AssertionResult(AssertionInfo const& info, AssertionResultData const& data);
5882
5883         bool isOk() const;
5884         bool succeeded() const;
5885         ResultWas::OfType getResultType() const;
5886         bool hasExpression() const;
5887         bool hasMessage() const;
5888         std::string getExpression() const;
5889         std::string getExpressionInMacro() const;
5890         bool hasExpandedExpression() const;
5891         std::string getExpandedExpression() const;
5892         std::string getMessage() const;
5893         SourceLineInfo getSourceInfo() const;
5894         StringRef getTestMacroName() const;
5895
5896         // protected:
5897         AssertionInfo m_info;
5898         AssertionResultData m_resultData;
5899     };
5900
5901 } // end namespace Catch
5902
5903 // end catch_assertionresult.h
5904 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5905 // start catch_estimate.hpp
5906
5907 // Statistics estimates
5908
5909 namespace Catch {
5910     namespace Benchmark {
5911         template <typename Duration> struct Estimate {
5912             Duration point;
5913             Duration lower_bound;
5914             Duration upper_bound;
5915             double confidence_interval;
5916
5917             template <typename Duration2> operator Estimate<Duration2>() const {
5918                 return {point, lower_bound, upper_bound, confidence_interval};
5919             }
5920         };
5921     } // namespace Benchmark
5922 } // namespace Catch
5923
5924 // end catch_estimate.hpp
5925 // start catch_outlier_classification.hpp
5926
5927 // Outlier information
5928
5929 namespace Catch {
5930     namespace Benchmark {
5931         struct OutlierClassification {
5932             int samples_seen = 0;
5933             int low_severe = 0;  // more than 3 times IQR below Q1
5934             int low_mild = 0;    // 1.5 to 3 times IQR below Q1
5935             int high_mild = 0;   // 1.5 to 3 times IQR above Q3
5936             int high_severe = 0; // more than 3 times IQR above Q3
5937
5938             int total() const { return low_severe + low_mild + high_mild + high_severe; }
5939         };
5940     } // namespace Benchmark
5941 } // namespace Catch
5942
5943 // end catch_outlier_classification.hpp
5944
5945 #include <iterator>
5946 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5947
5948 #include <string>
5949 #include <iosfwd>
5950 #include <map>
5951 #include <set>
5952 #include <memory>
5953 #include <algorithm>
5954
5955 namespace Catch {
5956
5957     struct ReporterConfig {
5958         explicit ReporterConfig(IConfigPtr const& _fullConfig);
5959
5960         ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream);
5961
5962         std::ostream& stream() const;
5963         IConfigPtr fullConfig() const;
5964
5965     private:
5966         std::ostream* m_stream;
5967         IConfigPtr m_fullConfig;
5968     };
5969
5970     struct ReporterPreferences {
5971         bool shouldRedirectStdOut = false;
5972         bool shouldReportAllAssertions = false;
5973     };
5974
5975     template <typename T> struct LazyStat : Option<T> {
5976         LazyStat& operator=(T const& _value) {
5977             Option<T>::operator=(_value);
5978             used = false;
5979             return *this;
5980         }
5981         void reset() {
5982             Option<T>::reset();
5983             used = false;
5984         }
5985         bool used = false;
5986     };
5987
5988     struct TestRunInfo {
5989         TestRunInfo(std::string const& _name);
5990         std::string name;
5991     };
5992     struct GroupInfo {
5993         GroupInfo(std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount);
5994
5995         std::string name;
5996         std::size_t groupIndex;
5997         std::size_t groupsCounts;
5998     };
5999
6000     struct AssertionStats {
6001         AssertionStats(AssertionResult const& _assertionResult,
6002                        std::vector<MessageInfo> const& _infoMessages,
6003                        Totals const& _totals);
6004
6005         AssertionStats(AssertionStats const&) = default;
6006         AssertionStats(AssertionStats&&) = default;
6007         AssertionStats& operator=(AssertionStats const&) = delete;
6008         AssertionStats& operator=(AssertionStats&&) = delete;
6009         virtual ~AssertionStats();
6010
6011         AssertionResult assertionResult;
6012         std::vector<MessageInfo> infoMessages;
6013         Totals totals;
6014     };
6015
6016     struct SectionStats {
6017         SectionStats(SectionInfo const& _sectionInfo,
6018                      Counts const& _assertions,
6019                      double _durationInSeconds,
6020                      bool _missingAssertions);
6021         SectionStats(SectionStats const&) = default;
6022         SectionStats(SectionStats&&) = default;
6023         SectionStats& operator=(SectionStats const&) = default;
6024         SectionStats& operator=(SectionStats&&) = default;
6025         virtual ~SectionStats();
6026
6027         SectionInfo sectionInfo;
6028         Counts assertions;
6029         double durationInSeconds;
6030         bool missingAssertions;
6031     };
6032
6033     struct TestCaseStats {
6034         TestCaseStats(TestCaseInfo const& _testInfo,
6035                       Totals const& _totals,
6036                       std::string const& _stdOut,
6037                       std::string const& _stdErr,
6038                       bool _aborting);
6039
6040         TestCaseStats(TestCaseStats const&) = default;
6041         TestCaseStats(TestCaseStats&&) = default;
6042         TestCaseStats& operator=(TestCaseStats const&) = default;
6043         TestCaseStats& operator=(TestCaseStats&&) = default;
6044         virtual ~TestCaseStats();
6045
6046         TestCaseInfo testInfo;
6047         Totals totals;
6048         std::string stdOut;
6049         std::string stdErr;
6050         bool aborting;
6051     };
6052
6053     struct TestGroupStats {
6054         TestGroupStats(GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting);
6055         TestGroupStats(GroupInfo const& _groupInfo);
6056
6057         TestGroupStats(TestGroupStats const&) = default;
6058         TestGroupStats(TestGroupStats&&) = default;
6059         TestGroupStats& operator=(TestGroupStats const&) = default;
6060         TestGroupStats& operator=(TestGroupStats&&) = default;
6061         virtual ~TestGroupStats();
6062
6063         GroupInfo groupInfo;
6064         Totals totals;
6065         bool aborting;
6066     };
6067
6068     struct TestRunStats {
6069         TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting);
6070
6071         TestRunStats(TestRunStats const&) = default;
6072         TestRunStats(TestRunStats&&) = default;
6073         TestRunStats& operator=(TestRunStats const&) = default;
6074         TestRunStats& operator=(TestRunStats&&) = default;
6075         virtual ~TestRunStats();
6076
6077         TestRunInfo runInfo;
6078         Totals totals;
6079         bool aborting;
6080     };
6081
6082 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6083     struct BenchmarkInfo {
6084         std::string name;
6085         double estimatedDuration;
6086         int iterations;
6087         int samples;
6088         unsigned int resamples;
6089         double clockResolution;
6090         double clockCost;
6091     };
6092
6093     template <class Duration> struct BenchmarkStats {
6094         BenchmarkInfo info;
6095
6096         std::vector<Duration> samples;
6097         Benchmark::Estimate<Duration> mean;
6098         Benchmark::Estimate<Duration> standardDeviation;
6099         Benchmark::OutlierClassification outliers;
6100         double outlierVariance;
6101
6102         template <typename Duration2> operator BenchmarkStats<Duration2>() const {
6103             std::vector<Duration2> samples2;
6104             samples2.reserve(samples.size());
6105             std::transform(samples.begin(),
6106                            samples.end(),
6107                            std::back_inserter(samples2),
6108                            [](Duration d) { return Duration2(d); });
6109             return {
6110                 info,
6111                 std::move(samples2),
6112                 mean,
6113                 standardDeviation,
6114                 outliers,
6115                 outlierVariance,
6116             };
6117         }
6118     };
6119 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6120
6121     struct IStreamingReporter {
6122         virtual ~IStreamingReporter() = default;
6123
6124         // Implementing class must also provide the following static methods:
6125         // static std::string getDescription();
6126         // static std::set<Verbosity> getSupportedVerbosities()
6127
6128         virtual ReporterPreferences getPreferences() const = 0;
6129
6130         virtual void noMatchingTestCases(std::string const& spec) = 0;
6131
6132         virtual void reportInvalidArguments(std::string const&) {}
6133
6134         virtual void testRunStarting(TestRunInfo const& testRunInfo) = 0;
6135         virtual void testGroupStarting(GroupInfo const& groupInfo) = 0;
6136
6137         virtual void testCaseStarting(TestCaseInfo const& testInfo) = 0;
6138         virtual void sectionStarting(SectionInfo const& sectionInfo) = 0;
6139
6140 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6141         virtual void benchmarkPreparing(std::string const&) {}
6142         virtual void benchmarkStarting(BenchmarkInfo const&) {}
6143         virtual void benchmarkEnded(BenchmarkStats<> const&) {}
6144         virtual void benchmarkFailed(std::string const&) {}
6145 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6146
6147         virtual void assertionStarting(AssertionInfo const& assertionInfo) = 0;
6148
6149         // The return value indicates if the messages buffer should be cleared:
6150         virtual bool assertionEnded(AssertionStats const& assertionStats) = 0;
6151
6152         virtual void sectionEnded(SectionStats const& sectionStats) = 0;
6153         virtual void testCaseEnded(TestCaseStats const& testCaseStats) = 0;
6154         virtual void testGroupEnded(TestGroupStats const& testGroupStats) = 0;
6155         virtual void testRunEnded(TestRunStats const& testRunStats) = 0;
6156
6157         virtual void skipTest(TestCaseInfo const& testInfo) = 0;
6158
6159         // Default empty implementation provided
6160         virtual void fatalErrorEncountered(StringRef name);
6161
6162         virtual bool isMulti() const;
6163     };
6164     using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
6165
6166     struct IReporterFactory {
6167         virtual ~IReporterFactory();
6168         virtual IStreamingReporterPtr create(ReporterConfig const& config) const = 0;
6169         virtual std::string getDescription() const = 0;
6170     };
6171     using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
6172
6173     struct IReporterRegistry {
6174         using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
6175         using Listeners = std::vector<IReporterFactoryPtr>;
6176
6177         virtual ~IReporterRegistry();
6178         virtual IStreamingReporterPtr create(std::string const& name,
6179                                              IConfigPtr const& config) const = 0;
6180         virtual FactoryMap const& getFactories() const = 0;
6181         virtual Listeners const& getListeners() const = 0;
6182     };
6183
6184 } // end namespace Catch
6185
6186 // end catch_interfaces_reporter.h
6187 #include <algorithm>
6188 #include <cstring>
6189 #include <cfloat>
6190 #include <cstdio>
6191 #include <cassert>
6192 #include <memory>
6193 #include <ostream>
6194
6195 namespace Catch {
6196     void prepareExpandedExpression(AssertionResult& result);
6197
6198     // Returns double formatted as %.3f (format expected on output)
6199     std::string getFormattedDuration(double duration);
6200
6201     //! Should the reporter show
6202     bool shouldShowDuration(IConfig const& config, double duration);
6203
6204     std::string serializeFilters(std::vector<std::string> const& container);
6205
6206     template <typename DerivedT> struct StreamingReporterBase : IStreamingReporter {
6207
6208         StreamingReporterBase(ReporterConfig const& _config) :
6209             m_config(_config.fullConfig()), stream(_config.stream()) {
6210             m_reporterPrefs.shouldRedirectStdOut = false;
6211             if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6212                 CATCH_ERROR("Verbosity level not supported by this reporter");
6213         }
6214
6215         ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6216
6217         static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6218
6219         ~StreamingReporterBase() override = default;
6220
6221         void noMatchingTestCases(std::string const&) override {}
6222
6223         void reportInvalidArguments(std::string const&) override {}
6224
6225         void testRunStarting(TestRunInfo const& _testRunInfo) override {
6226             currentTestRunInfo = _testRunInfo;
6227         }
6228
6229         void testGroupStarting(GroupInfo const& _groupInfo) override {
6230             currentGroupInfo = _groupInfo;
6231         }
6232
6233         void testCaseStarting(TestCaseInfo const& _testInfo) override {
6234             currentTestCaseInfo = _testInfo;
6235         }
6236         void sectionStarting(SectionInfo const& _sectionInfo) override {
6237             m_sectionStack.push_back(_sectionInfo);
6238         }
6239
6240         void sectionEnded(SectionStats const& /* _sectionStats */) override {
6241             m_sectionStack.pop_back();
6242         }
6243         void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
6244             currentTestCaseInfo.reset();
6245         }
6246         void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
6247             currentGroupInfo.reset();
6248         }
6249         void testRunEnded(TestRunStats const& /* _testRunStats */) override {
6250             currentTestCaseInfo.reset();
6251             currentGroupInfo.reset();
6252             currentTestRunInfo.reset();
6253         }
6254
6255         void skipTest(TestCaseInfo const&) override {
6256             // Don't do anything with this by default.
6257             // It can optionally be overridden in the derived class.
6258         }
6259
6260         IConfigPtr m_config;
6261         std::ostream& stream;
6262
6263         LazyStat<TestRunInfo> currentTestRunInfo;
6264         LazyStat<GroupInfo> currentGroupInfo;
6265         LazyStat<TestCaseInfo> currentTestCaseInfo;
6266
6267         std::vector<SectionInfo> m_sectionStack;
6268         ReporterPreferences m_reporterPrefs;
6269     };
6270
6271     template <typename DerivedT> struct CumulativeReporterBase : IStreamingReporter {
6272         template <typename T, typename ChildNodeT> struct Node {
6273             explicit Node(T const& _value) : value(_value) {}
6274             virtual ~Node() {}
6275
6276             using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
6277             T value;
6278             ChildNodes children;
6279         };
6280         struct SectionNode {
6281             explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
6282             virtual ~SectionNode() = default;
6283
6284             bool operator==(SectionNode const& other) const {
6285                 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
6286             }
6287             bool operator==(std::shared_ptr<SectionNode> const& other) const {
6288                 return operator==(*other);
6289             }
6290
6291             SectionStats stats;
6292             using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
6293             using Assertions = std::vector<AssertionStats>;
6294             ChildSections childSections;
6295             Assertions assertions;
6296             std::string stdOut;
6297             std::string stdErr;
6298         };
6299
6300         struct BySectionInfo {
6301             BySectionInfo(SectionInfo const& other) : m_other(other) {}
6302             BySectionInfo(BySectionInfo const& other) : m_other(other.m_other) {}
6303             bool operator()(std::shared_ptr<SectionNode> const& node) const {
6304                 return ((node->stats.sectionInfo.name == m_other.name) &&
6305                         (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
6306             }
6307             void operator=(BySectionInfo const&) = delete;
6308
6309         private:
6310             SectionInfo const& m_other;
6311         };
6312
6313         using TestCaseNode = Node<TestCaseStats, SectionNode>;
6314         using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
6315         using TestRunNode = Node<TestRunStats, TestGroupNode>;
6316
6317         CumulativeReporterBase(ReporterConfig const& _config) :
6318             m_config(_config.fullConfig()), stream(_config.stream()) {
6319             m_reporterPrefs.shouldRedirectStdOut = false;
6320             if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6321                 CATCH_ERROR("Verbosity level not supported by this reporter");
6322         }
6323         ~CumulativeReporterBase() override = default;
6324
6325         ReporterPreferences getPreferences() const override { return m_reporterPrefs; }
6326
6327         static std::set<Verbosity> getSupportedVerbosities() { return {Verbosity::Normal}; }
6328
6329         void testRunStarting(TestRunInfo const&) override {}
6330         void testGroupStarting(GroupInfo const&) override {}
6331
6332         void testCaseStarting(TestCaseInfo const&) override {}
6333
6334         void sectionStarting(SectionInfo const& sectionInfo) override {
6335             SectionStats incompleteStats(sectionInfo, Counts(), 0, false);
6336             std::shared_ptr<SectionNode> node;
6337             if (m_sectionStack.empty()) {
6338                 if (!m_rootSection)
6339                     m_rootSection = std::make_shared<SectionNode>(incompleteStats);
6340                 node = m_rootSection;
6341             } else {
6342                 SectionNode& parentNode = *m_sectionStack.back();
6343                 auto it = std::find_if(parentNode.childSections.begin(),
6344                                        parentNode.childSections.end(),
6345                                        BySectionInfo(sectionInfo));
6346                 if (it == parentNode.childSections.end()) {
6347                     node = std::make_shared<SectionNode>(incompleteStats);
6348                     parentNode.childSections.push_back(node);
6349                 } else
6350                     node = *it;
6351             }
6352             m_sectionStack.push_back(node);
6353             m_deepestSection = std::move(node);
6354         }
6355
6356         void assertionStarting(AssertionInfo const&) override {}
6357
6358         bool assertionEnded(AssertionStats const& assertionStats) override {
6359             assert(!m_sectionStack.empty());
6360             // AssertionResult holds a pointer to a temporary
6361             // DecomposedExpression, which getExpandedExpression() calls to
6362             // build the expression string. Our section stack copy of the
6363             // assertionResult will likely outlive the temporary, so it must be
6364             // expanded or discarded now to avoid calling a destroyed object
6365             // later.
6366             prepareExpandedExpression(const_cast<AssertionResult&>(assertionStats.assertionResult));
6367             SectionNode& sectionNode = *m_sectionStack.back();
6368             sectionNode.assertions.push_back(assertionStats);
6369             return true;
6370         }
6371         void sectionEnded(SectionStats const& sectionStats) override {
6372             assert(!m_sectionStack.empty());
6373             SectionNode& node = *m_sectionStack.back();
6374             node.stats = sectionStats;
6375             m_sectionStack.pop_back();
6376         }
6377         void testCaseEnded(TestCaseStats const& testCaseStats) override {
6378             auto node = std::make_shared<TestCaseNode>(testCaseStats);
6379             assert(m_sectionStack.size() == 0);
6380             node->children.push_back(m_rootSection);
6381             m_testCases.push_back(node);
6382             m_rootSection.reset();
6383
6384             assert(m_deepestSection);
6385             m_deepestSection->stdOut = testCaseStats.stdOut;
6386             m_deepestSection->stdErr = testCaseStats.stdErr;
6387         }
6388         void testGroupEnded(TestGroupStats const& testGroupStats) override {
6389             auto node = std::make_shared<TestGroupNode>(testGroupStats);
6390             node->children.swap(m_testCases);
6391             m_testGroups.push_back(node);
6392         }
6393         void testRunEnded(TestRunStats const& testRunStats) override {
6394             auto node = std::make_shared<TestRunNode>(testRunStats);
6395             node->children.swap(m_testGroups);
6396             m_testRuns.push_back(node);
6397             testRunEndedCumulative();
6398         }
6399         virtual void testRunEndedCumulative() = 0;
6400
6401         void skipTest(TestCaseInfo const&) override {}
6402
6403         IConfigPtr m_config;
6404         std::ostream& stream;
6405         std::vector<AssertionStats> m_assertions;
6406         std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
6407         std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
6408         std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
6409
6410         std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
6411
6412         std::shared_ptr<SectionNode> m_rootSection;
6413         std::shared_ptr<SectionNode> m_deepestSection;
6414         std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
6415         ReporterPreferences m_reporterPrefs;
6416     };
6417
6418     template <char C> char const* getLineOfChars() {
6419         static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
6420         if (!*line) {
6421             std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1);
6422             line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0;
6423         }
6424         return line;
6425     }
6426
6427     struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
6428         TestEventListenerBase(ReporterConfig const& _config);
6429
6430         static std::set<Verbosity> getSupportedVerbosities();
6431
6432         void assertionStarting(AssertionInfo const&) override;
6433         bool assertionEnded(AssertionStats const&) override;
6434     };
6435
6436 } // end namespace Catch
6437
6438 // end catch_reporter_bases.hpp
6439 // start catch_console_colour.h
6440
6441 namespace Catch {
6442
6443     struct Colour {
6444         enum Code {
6445             None = 0,
6446
6447             White,
6448             Red,
6449             Green,
6450             Blue,
6451             Cyan,
6452             Yellow,
6453             Grey,
6454
6455             Bright = 0x10,
6456
6457             BrightRed = Bright | Red,
6458             BrightGreen = Bright | Green,
6459             LightGrey = Bright | Grey,
6460             BrightWhite = Bright | White,
6461             BrightYellow = Bright | Yellow,
6462
6463             // By intention
6464             FileName = LightGrey,
6465             Warning = BrightYellow,
6466             ResultError = BrightRed,
6467             ResultSuccess = BrightGreen,
6468             ResultExpectedFailure = Warning,
6469
6470             Error = BrightRed,
6471             Success = Green,
6472
6473             OriginalExpression = Cyan,
6474             ReconstructedExpression = BrightYellow,
6475
6476             SecondaryText = LightGrey,
6477             Headers = White
6478         };
6479
6480         // Use constructed object for RAII guard
6481         Colour(Code _colourCode);
6482         Colour(Colour&& other) noexcept;
6483         Colour& operator=(Colour&& other) noexcept;
6484         ~Colour();
6485
6486         // Use static method for one-shot changes
6487         static void use(Code _colourCode);
6488
6489     private:
6490         bool m_moved = false;
6491     };
6492
6493     std::ostream& operator<<(std::ostream& os, Colour const&);
6494
6495 } // end namespace Catch
6496
6497 // end catch_console_colour.h
6498 // start catch_reporter_registrars.hpp
6499
6500 namespace Catch {
6501
6502     template <typename T> class ReporterRegistrar {
6503
6504         class ReporterFactory : public IReporterFactory {
6505
6506             IStreamingReporterPtr create(ReporterConfig const& config) const override {
6507                 return std::unique_ptr<T>(new T(config));
6508             }
6509
6510             std::string getDescription() const override { return T::getDescription(); }
6511         };
6512
6513     public:
6514         explicit ReporterRegistrar(std::string const& name) {
6515             getMutableRegistryHub().registerReporter(name, std::make_shared<ReporterFactory>());
6516         }
6517     };
6518
6519     template <typename T> class ListenerRegistrar {
6520
6521         class ListenerFactory : public IReporterFactory {
6522
6523             IStreamingReporterPtr create(ReporterConfig const& config) const override {
6524                 return std::unique_ptr<T>(new T(config));
6525             }
6526             std::string getDescription() const override { return std::string(); }
6527         };
6528
6529     public:
6530         ListenerRegistrar() {
6531             getMutableRegistryHub().registerListener(std::make_shared<ListenerFactory>());
6532         }
6533     };
6534 } // namespace Catch
6535
6536 #if !defined(CATCH_CONFIG_DISABLE)
6537
6538 #define CATCH_REGISTER_REPORTER(name, reporterType)                                                \
6539     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
6540     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
6541     namespace {                                                                                    \
6542         Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType(name);    \
6543     }                                                                                              \
6544     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6545
6546 #define CATCH_REGISTER_LISTENER(listenerType)                                                      \
6547     CATCH_INTERNAL_START_WARNINGS_SUPPRESSION                                                      \
6548     CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS                                                       \
6549     namespace {                                                                                    \
6550         Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType;          \
6551     }                                                                                              \
6552     CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6553 #else // CATCH_CONFIG_DISABLE
6554
6555 #define CATCH_REGISTER_REPORTER(name, reporterType)
6556 #define CATCH_REGISTER_LISTENER(listenerType)
6557
6558 #endif // CATCH_CONFIG_DISABLE
6559
6560 // end catch_reporter_registrars.hpp
6561 // Allow users to base their work off existing reporters
6562 // start catch_reporter_compact.h
6563
6564 namespace Catch {
6565
6566     struct CompactReporter : StreamingReporterBase<CompactReporter> {
6567
6568         using StreamingReporterBase::StreamingReporterBase;
6569
6570         ~CompactReporter() override;
6571
6572         static std::string getDescription();
6573
6574         void noMatchingTestCases(std::string const& spec) override;
6575
6576         void assertionStarting(AssertionInfo const&) override;
6577
6578         bool assertionEnded(AssertionStats const& _assertionStats) override;
6579
6580         void sectionEnded(SectionStats const& _sectionStats) override;
6581
6582         void testRunEnded(TestRunStats const& _testRunStats) override;
6583     };
6584
6585 } // end namespace Catch
6586
6587 // end catch_reporter_compact.h
6588 // start catch_reporter_console.h
6589
6590 #if defined(_MSC_VER)
6591 #pragma warning(push)
6592 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
6593                                 // switch Note that 4062 (not all labels are
6594                                 // handled and default is missing) is enabled
6595 #endif
6596
6597 namespace Catch {
6598     // Fwd decls
6599     struct SummaryColumn;
6600     class TablePrinter;
6601
6602     struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6603         std::unique_ptr<TablePrinter> m_tablePrinter;
6604
6605         ConsoleReporter(ReporterConfig const& config);
6606         ~ConsoleReporter() override;
6607         static std::string getDescription();
6608
6609         void noMatchingTestCases(std::string const& spec) override;
6610
6611         void reportInvalidArguments(std::string const& arg) override;
6612
6613         void assertionStarting(AssertionInfo const&) override;
6614
6615         bool assertionEnded(AssertionStats const& _assertionStats) override;
6616
6617         void sectionStarting(SectionInfo const& _sectionInfo) override;
6618         void sectionEnded(SectionStats const& _sectionStats) override;
6619
6620 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6621         void benchmarkPreparing(std::string const& name) override;
6622         void benchmarkStarting(BenchmarkInfo const& info) override;
6623         void benchmarkEnded(BenchmarkStats<> const& stats) override;
6624         void benchmarkFailed(std::string const& error) override;
6625 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6626
6627         void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6628         void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6629         void testRunEnded(TestRunStats const& _testRunStats) override;
6630         void testRunStarting(TestRunInfo const& _testRunInfo) override;
6631
6632     private:
6633         void lazyPrint();
6634
6635         void lazyPrintWithoutClosingBenchmarkTable();
6636         void lazyPrintRunInfo();
6637         void lazyPrintGroupInfo();
6638         void printTestCaseAndSectionHeader();
6639
6640         void printClosedHeader(std::string const& _name);
6641         void printOpenHeader(std::string const& _name);
6642
6643         // if string has a : in first line will set indent to follow it on
6644         // subsequent lines
6645         void printHeaderString(std::string const& _string, std::size_t indent = 0);
6646
6647         void printTotals(Totals const& totals);
6648         void printSummaryRow(std::string const& label,
6649                              std::vector<SummaryColumn> const& cols,
6650                              std::size_t row);
6651
6652         void printTotalsDivider(Totals const& totals);
6653         void printSummaryDivider();
6654         void printTestFilters();
6655
6656     private:
6657         bool m_headerPrinted = false;
6658     };
6659
6660 } // end namespace Catch
6661
6662 #if defined(_MSC_VER)
6663 #pragma warning(pop)
6664 #endif
6665
6666 // end catch_reporter_console.h
6667 // start catch_reporter_junit.h
6668
6669 // start catch_xmlwriter.h
6670
6671 #include <vector>
6672
6673 namespace Catch {
6674     enum class XmlFormatting {
6675         None = 0x00,
6676         Indent = 0x01,
6677         Newline = 0x02,
6678     };
6679
6680     XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs);
6681     XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs);
6682
6683     class XmlEncode {
6684     public:
6685         enum ForWhat { ForTextNodes, ForAttributes };
6686
6687         XmlEncode(std::string const& str, ForWhat forWhat = ForTextNodes);
6688
6689         void encodeTo(std::ostream& os) const;
6690
6691         friend std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode);
6692
6693     private:
6694         std::string m_str;
6695         ForWhat m_forWhat;
6696     };
6697
6698     class XmlWriter {
6699     public:
6700         class ScopedElement {
6701         public:
6702             ScopedElement(XmlWriter* writer, XmlFormatting fmt);
6703
6704             ScopedElement(ScopedElement&& other) noexcept;
6705             ScopedElement& operator=(ScopedElement&& other) noexcept;
6706
6707             ~ScopedElement();
6708
6709             ScopedElement& writeText(std::string const& text,
6710                                      XmlFormatting fmt = XmlFormatting::Newline |
6711                                                          XmlFormatting::Indent);
6712
6713             template <typename T>
6714             ScopedElement& writeAttribute(std::string const& name, T const& attribute) {
6715                 m_writer->writeAttribute(name, attribute);
6716                 return *this;
6717             }
6718
6719         private:
6720             mutable XmlWriter* m_writer = nullptr;
6721             XmlFormatting m_fmt;
6722         };
6723
6724         XmlWriter(std::ostream& os = Catch::cout());
6725         ~XmlWriter();
6726
6727         XmlWriter(XmlWriter const&) = delete;
6728         XmlWriter& operator=(XmlWriter const&) = delete;
6729
6730         XmlWriter& startElement(std::string const& name,
6731                                 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6732
6733         ScopedElement scopedElement(std::string const& name,
6734                                     XmlFormatting fmt = XmlFormatting::Newline |
6735                                                         XmlFormatting::Indent);
6736
6737         XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6738
6739         XmlWriter& writeAttribute(std::string const& name, std::string const& attribute);
6740
6741         XmlWriter& writeAttribute(std::string const& name, bool attribute);
6742
6743         template <typename T>
6744         XmlWriter& writeAttribute(std::string const& name, T const& attribute) {
6745             ReusableStringStream rss;
6746             rss << attribute;
6747             return writeAttribute(name, rss.str());
6748         }
6749
6750         XmlWriter& writeText(std::string const& text,
6751                              XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6752
6753         XmlWriter& writeComment(std::string const& text,
6754                                 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6755
6756         void writeStylesheetRef(std::string const& url);
6757
6758         XmlWriter& writeBlankLine();
6759
6760         void ensureTagClosed();
6761
6762     private:
6763         void applyFormatting(XmlFormatting fmt);
6764
6765         void writeDeclaration();
6766
6767         void newlineIfNecessary();
6768
6769         bool m_tagIsOpen = false;
6770         bool m_needsNewline = false;
6771         std::vector<std::string> m_tags;
6772         std::string m_indent;
6773         std::ostream& m_os;
6774     };
6775
6776 } // namespace Catch
6777
6778 // end catch_xmlwriter.h
6779 namespace Catch {
6780
6781     class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6782     public:
6783         JunitReporter(ReporterConfig const& _config);
6784
6785         ~JunitReporter() override;
6786
6787         static std::string getDescription();
6788
6789         void noMatchingTestCases(std::string const& /*spec*/) override;
6790
6791         void testRunStarting(TestRunInfo const& runInfo) override;
6792
6793         void testGroupStarting(GroupInfo const& groupInfo) override;
6794
6795         void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6796         bool assertionEnded(AssertionStats const& assertionStats) override;
6797
6798         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6799
6800         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6801
6802         void testRunEndedCumulative() override;
6803
6804         void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6805
6806         void writeTestCase(TestCaseNode const& testCaseNode);
6807
6808         void writeSection(std::string const& className,
6809                           std::string const& rootName,
6810                           SectionNode const& sectionNode,
6811                           bool testOkToFail);
6812
6813         void writeAssertions(SectionNode const& sectionNode);
6814         void writeAssertion(AssertionStats const& stats);
6815
6816         XmlWriter xml;
6817         Timer suiteTimer;
6818         std::string stdOutForSuite;
6819         std::string stdErrForSuite;
6820         unsigned int unexpectedExceptions = 0;
6821         bool m_okToFail = false;
6822     };
6823
6824 } // end namespace Catch
6825
6826 // end catch_reporter_junit.h
6827 // start catch_reporter_xml.h
6828
6829 namespace Catch {
6830     class XmlReporter : public StreamingReporterBase<XmlReporter> {
6831     public:
6832         XmlReporter(ReporterConfig const& _config);
6833
6834         ~XmlReporter() override;
6835
6836         static std::string getDescription();
6837
6838         virtual std::string getStylesheetRef() const;
6839
6840         void writeSourceInfo(SourceLineInfo const& sourceInfo);
6841
6842     public: // StreamingReporterBase
6843         void noMatchingTestCases(std::string const& s) override;
6844
6845         void testRunStarting(TestRunInfo const& testInfo) override;
6846
6847         void testGroupStarting(GroupInfo const& groupInfo) override;
6848
6849         void testCaseStarting(TestCaseInfo const& testInfo) override;
6850
6851         void sectionStarting(SectionInfo const& sectionInfo) override;
6852
6853         void assertionStarting(AssertionInfo const&) override;
6854
6855         bool assertionEnded(AssertionStats const& assertionStats) override;
6856
6857         void sectionEnded(SectionStats const& sectionStats) override;
6858
6859         void testCaseEnded(TestCaseStats const& testCaseStats) override;
6860
6861         void testGroupEnded(TestGroupStats const& testGroupStats) override;
6862
6863         void testRunEnded(TestRunStats const& testRunStats) override;
6864
6865 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6866         void benchmarkPreparing(std::string const& name) override;
6867         void benchmarkStarting(BenchmarkInfo const&) override;
6868         void benchmarkEnded(BenchmarkStats<> const&) override;
6869         void benchmarkFailed(std::string const&) override;
6870 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6871
6872     private:
6873         Timer m_testCaseTimer;
6874         XmlWriter m_xml;
6875         int m_sectionDepth = 0;
6876     };
6877
6878 } // end namespace Catch
6879
6880 // end catch_reporter_xml.h
6881
6882 // end catch_external_interfaces.h
6883 #endif
6884
6885 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6886 // start catch_benchmarking_all.hpp
6887
6888 // A proxy header that includes all of the benchmarking headers to allow
6889 // concise include of the benchmarking features. You should prefer the
6890 // individual includes in standard use.
6891
6892 // start catch_benchmark.hpp
6893
6894 // Benchmark
6895
6896 // start catch_chronometer.hpp
6897
6898 // User-facing chronometer
6899
6900 // start catch_clock.hpp
6901
6902 // Clocks
6903
6904 #include <chrono>
6905 #include <ratio>
6906
6907 namespace Catch {
6908     namespace Benchmark {
6909         template <typename Clock> using ClockDuration = typename Clock::duration;
6910         template <typename Clock>
6911         using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6912
6913         template <typename Clock> using TimePoint = typename Clock::time_point;
6914
6915         using default_clock = std::chrono::steady_clock;
6916
6917         template <typename Clock> struct now {
6918             TimePoint<Clock> operator()() const { return Clock::now(); }
6919         };
6920
6921         using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6922     } // namespace Benchmark
6923 } // namespace Catch
6924
6925 // end catch_clock.hpp
6926 // start catch_optimizer.hpp
6927
6928 // Hinting the optimizer
6929
6930 #if defined(_MSC_VER)
6931 #include <atomic> // atomic_thread_fence
6932 #endif
6933
6934 namespace Catch {
6935     namespace Benchmark {
6936 #if defined(__GNUC__) || defined(__clang__)
6937         template <typename T> inline void keep_memory(T* p) {
6938             asm volatile("" : : "g"(p) : "memory");
6939         }
6940         inline void keep_memory() { asm volatile("" : : : "memory"); }
6941
6942         namespace Detail {
6943             inline void optimizer_barrier() { keep_memory(); }
6944         } // namespace Detail
6945 #elif defined(_MSC_VER)
6946
6947 #pragma optimize("", off)
6948         template <typename T> inline void keep_memory(T* p) {
6949             // thanks @milleniumbug
6950             *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6951         }
6952         // TODO equivalent keep_memory()
6953 #pragma optimize("", on)
6954
6955         namespace Detail {
6956             inline void optimizer_barrier() { std::atomic_thread_fence(std::memory_order_seq_cst); }
6957         } // namespace Detail
6958
6959 #endif
6960
6961         template <typename T> inline void deoptimize_value(T&& x) { keep_memory(&x); }
6962
6963         template <typename Fn, typename... Args>
6964         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6965             typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6966             deoptimize_value(std::forward<Fn>(fn)(std::forward<Args...>(args...)));
6967         }
6968
6969         template <typename Fn, typename... Args>
6970         inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6971             typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6972             std::forward<Fn>(fn)(std::forward<Args...>(args...));
6973         }
6974     } // namespace Benchmark
6975 } // namespace Catch
6976
6977 // end catch_optimizer.hpp
6978 // start catch_complete_invoke.hpp
6979
6980 // Invoke with a special case for void
6981
6982 #include <type_traits>
6983 #include <utility>
6984
6985 namespace Catch {
6986     namespace Benchmark {
6987         namespace Detail {
6988             template <typename T> struct CompleteType { using type = T; };
6989             template <> struct CompleteType<void> {
6990                 struct type {};
6991             };
6992
6993             template <typename T> using CompleteType_t = typename CompleteType<T>::type;
6994
6995             template <typename Result> struct CompleteInvoker {
6996                 template <typename Fun, typename... Args>
6997                 static Result invoke(Fun&& fun, Args&&... args) {
6998                     return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6999                 }
7000             };
7001             template <> struct CompleteInvoker<void> {
7002                 template <typename Fun, typename... Args>
7003                 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
7004                     std::forward<Fun>(fun)(std::forward<Args>(args)...);
7005                     return {};
7006                 }
7007             };
7008
7009             // invoke and not return void :(
7010             template <typename Fun, typename... Args>
7011             CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun,
7012                                                                              Args&&... args) {
7013                 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(
7014                     std::forward<Fun>(fun), std::forward<Args>(args)...);
7015             }
7016
7017             const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
7018         } // namespace Detail
7019
7020         template <typename Fun>
7021         Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
7022             CATCH_TRY { return Detail::complete_invoke(std::forward<Fun>(fun)); }
7023             CATCH_CATCH_ALL {
7024                 getResultCapture().benchmarkFailed(translateActiveException());
7025                 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
7026             }
7027         }
7028     } // namespace Benchmark
7029 } // namespace Catch
7030
7031 // end catch_complete_invoke.hpp
7032 namespace Catch {
7033     namespace Benchmark {
7034         namespace Detail {
7035             struct ChronometerConcept {
7036                 virtual void start() = 0;
7037                 virtual void finish() = 0;
7038                 virtual ~ChronometerConcept() = default;
7039             };
7040             template <typename Clock> struct ChronometerModel final : public ChronometerConcept {
7041                 void start() override { started = Clock::now(); }
7042                 void finish() override { finished = Clock::now(); }
7043
7044                 ClockDuration<Clock> elapsed() const { return finished - started; }
7045
7046                 TimePoint<Clock> started;
7047                 TimePoint<Clock> finished;
7048             };
7049         } // namespace Detail
7050
7051         struct Chronometer {
7052         public:
7053             template <typename Fun> void measure(Fun&& fun) {
7054                 measure(std::forward<Fun>(fun), is_callable<Fun(int)>());
7055             }
7056
7057             int runs() const { return k; }
7058
7059             Chronometer(Detail::ChronometerConcept& meter, int k) : impl(&meter), k(k) {}
7060
7061         private:
7062             template <typename Fun> void measure(Fun&& fun, std::false_type) {
7063                 measure([&fun](int) { return fun(); }, std::true_type());
7064             }
7065
7066             template <typename Fun> void measure(Fun&& fun, std::true_type) {
7067                 Detail::optimizer_barrier();
7068                 impl->start();
7069                 for (int i = 0; i < k; ++i)
7070                     invoke_deoptimized(fun, i);
7071                 impl->finish();
7072                 Detail::optimizer_barrier();
7073             }
7074
7075             Detail::ChronometerConcept* impl;
7076             int k;
7077         };
7078     } // namespace Benchmark
7079 } // namespace Catch
7080
7081 // end catch_chronometer.hpp
7082 // start catch_environment.hpp
7083
7084 // Environment information
7085
7086 namespace Catch {
7087     namespace Benchmark {
7088         template <typename Duration> struct EnvironmentEstimate {
7089             Duration mean;
7090             OutlierClassification outliers;
7091
7092             template <typename Duration2> operator EnvironmentEstimate<Duration2>() const {
7093                 return {mean, outliers};
7094             }
7095         };
7096         template <typename Clock> struct Environment {
7097             using clock_type = Clock;
7098             EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
7099             EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
7100         };
7101     } // namespace Benchmark
7102 } // namespace Catch
7103
7104 // end catch_environment.hpp
7105 // start catch_execution_plan.hpp
7106
7107 // Execution plan
7108
7109 // start catch_benchmark_function.hpp
7110
7111 // Dumb std::function implementation for consistent call overhead
7112
7113 #include <cassert>
7114 #include <type_traits>
7115 #include <utility>
7116 #include <memory>
7117
7118 namespace Catch {
7119     namespace Benchmark {
7120         namespace Detail {
7121             template <typename T> using Decay = typename std::decay<T>::type;
7122             template <typename T, typename U>
7123             struct is_related : std::is_same<Decay<T>, Decay<U>> {};
7124
7125             /// We need to reinvent std::function because every piece of code
7126             /// that might add overhead in a measurement context needs to have
7127             /// consistent performance characteristics so that we can account
7128             /// for it in the measurement. Implementations of std::function with
7129             /// optimizations that aren't always applicable, like small buffer
7130             /// optimizations, are not uncommon. This is effectively an
7131             /// implementation of std::function without any such optimizations;
7132             /// it may be slow, but it is consistently slow.
7133             struct BenchmarkFunction {
7134             private:
7135                 struct callable {
7136                     virtual void call(Chronometer meter) const = 0;
7137                     virtual callable* clone() const = 0;
7138                     virtual ~callable() = default;
7139                 };
7140                 template <typename Fun> struct model : public callable {
7141                     model(Fun&& fun) : fun(std::move(fun)) {}
7142                     model(Fun const& fun) : fun(fun) {}
7143
7144                     model<Fun>* clone() const override { return new model<Fun>(*this); }
7145
7146                     void call(Chronometer meter) const override {
7147                         call(meter, is_callable<Fun(Chronometer)>());
7148                     }
7149                     void call(Chronometer meter, std::true_type) const { fun(meter); }
7150                     void call(Chronometer meter, std::false_type) const { meter.measure(fun); }
7151
7152                     Fun fun;
7153                 };
7154
7155                 struct do_nothing {
7156                     void operator()() const {}
7157                 };
7158
7159                 template <typename T> BenchmarkFunction(model<T>* c) : f(c) {}
7160
7161             public:
7162                 BenchmarkFunction() : f(new model<do_nothing>{{}}) {}
7163
7164                 template <typename Fun,
7165                           typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
7166                                                   int>::type = 0>
7167                 BenchmarkFunction(Fun&& fun) :
7168                     f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
7169
7170                 BenchmarkFunction(BenchmarkFunction&& that) : f(std::move(that.f)) {}
7171
7172                 BenchmarkFunction(BenchmarkFunction const& that) : f(that.f->clone()) {}
7173
7174                 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
7175                     f = std::move(that.f);
7176                     return *this;
7177                 }
7178
7179                 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
7180                     f.reset(that.f->clone());
7181                     return *this;
7182                 }
7183
7184                 void operator()(Chronometer meter) const { f->call(meter); }
7185
7186             private:
7187                 std::unique_ptr<callable> f;
7188             };
7189         } // namespace Detail
7190     }     // namespace Benchmark
7191 } // namespace Catch
7192
7193 // end catch_benchmark_function.hpp
7194 // start catch_repeat.hpp
7195
7196 // repeat algorithm
7197
7198 #include <type_traits>
7199 #include <utility>
7200
7201 namespace Catch {
7202     namespace Benchmark {
7203         namespace Detail {
7204             template <typename Fun> struct repeater {
7205                 void operator()(int k) const {
7206                     for (int i = 0; i < k; ++i) {
7207                         fun();
7208                     }
7209                 }
7210                 Fun fun;
7211             };
7212             template <typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
7213                 return {std::forward<Fun>(fun)};
7214             }
7215         } // namespace Detail
7216     }     // namespace Benchmark
7217 } // namespace Catch
7218
7219 // end catch_repeat.hpp
7220 // start catch_run_for_at_least.hpp
7221
7222 // Run a function for a minimum amount of time
7223
7224 // start catch_measure.hpp
7225
7226 // Measure
7227
7228 // start catch_timing.hpp
7229
7230 // Timing
7231
7232 #include <tuple>
7233 #include <type_traits>
7234
7235 namespace Catch {
7236     namespace Benchmark {
7237         template <typename Duration, typename Result> struct Timing {
7238             Duration elapsed;
7239             Result result;
7240             int iterations;
7241         };
7242         template <typename Clock, typename Func, typename... Args>
7243         using TimingOf =
7244             Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
7245     } // namespace Benchmark
7246 } // namespace Catch
7247
7248 // end catch_timing.hpp
7249 #include <utility>
7250
7251 namespace Catch {
7252     namespace Benchmark {
7253         namespace Detail {
7254             template <typename Clock, typename Fun, typename... Args>
7255             TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
7256                 auto start = Clock::now();
7257                 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
7258                 auto end = Clock::now();
7259                 auto delta = end - start;
7260                 return {delta, std::forward<decltype(r)>(r), 1};
7261             }
7262         } // namespace Detail
7263     }     // namespace Benchmark
7264 } // namespace Catch
7265
7266 // end catch_measure.hpp
7267 #include <utility>
7268 #include <type_traits>
7269
7270 namespace Catch {
7271     namespace Benchmark {
7272         namespace Detail {
7273             template <typename Clock, typename Fun>
7274             TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
7275                 return Detail::measure<Clock>(fun, iters);
7276             }
7277             template <typename Clock, typename Fun>
7278             TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
7279                 Detail::ChronometerModel<Clock> meter;
7280                 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
7281
7282                 return {meter.elapsed(), std::move(result), iters};
7283             }
7284
7285             template <typename Clock, typename Fun>
7286             using run_for_at_least_argument_t = typename std::
7287                 conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
7288
7289             struct optimized_away_error : std::exception {
7290                 const char* what() const noexcept override {
7291                     return "could not measure benchmark, maybe it was "
7292                            "optimized away";
7293                 }
7294             };
7295
7296             template <typename Clock, typename Fun>
7297             TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
7298             run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
7299                 auto iters = seed;
7300                 while (iters < (1 << 30)) {
7301                     auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
7302
7303                     if (Timing.elapsed >= how_long) {
7304                         return {Timing.elapsed, std::move(Timing.result), iters};
7305                     }
7306                     iters *= 2;
7307                 }
7308                 Catch::throw_exception(optimized_away_error{});
7309             }
7310         } // namespace Detail
7311     }     // namespace Benchmark
7312 } // namespace Catch
7313
7314 // end catch_run_for_at_least.hpp
7315 #include <algorithm>
7316 #include <iterator>
7317
7318 namespace Catch {
7319     namespace Benchmark {
7320         template <typename Duration> struct ExecutionPlan {
7321             int iterations_per_sample;
7322             Duration estimated_duration;
7323             Detail::BenchmarkFunction benchmark;
7324             Duration warmup_time;
7325             int warmup_iterations;
7326
7327             template <typename Duration2> operator ExecutionPlan<Duration2>() const {
7328                 return {iterations_per_sample,
7329                         estimated_duration,
7330                         benchmark,
7331                         warmup_time,
7332                         warmup_iterations};
7333             }
7334
7335             template <typename Clock>
7336             std::vector<FloatDuration<Clock>> run(const IConfig& cfg,
7337                                                   Environment<FloatDuration<Clock>> env) const {
7338                 // warmup a bit
7339                 Detail::run_for_at_least<Clock>(
7340                     std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7341                     warmup_iterations,
7342                     Detail::repeat(now<Clock>{}));
7343
7344                 std::vector<FloatDuration<Clock>> times;
7345                 times.reserve(cfg.benchmarkSamples());
7346                 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
7347                     Detail::ChronometerModel<Clock> model;
7348                     this->benchmark(Chronometer(model, iterations_per_sample));
7349                     auto sample_time = model.elapsed() - env.clock_cost.mean;
7350                     if (sample_time < FloatDuration<Clock>::zero())
7351                         sample_time = FloatDuration<Clock>::zero();
7352                     return sample_time / iterations_per_sample;
7353                 });
7354                 return times;
7355             }
7356         };
7357     } // namespace Benchmark
7358 } // namespace Catch
7359
7360 // end catch_execution_plan.hpp
7361 // start catch_estimate_clock.hpp
7362
7363 // Environment measurement
7364
7365 // start catch_stats.hpp
7366
7367 // Statistical analysis tools
7368
7369 #include <algorithm>
7370 #include <functional>
7371 #include <vector>
7372 #include <iterator>
7373 #include <numeric>
7374 #include <tuple>
7375 #include <cmath>
7376 #include <utility>
7377 #include <cstddef>
7378 #include <random>
7379
7380 namespace Catch {
7381     namespace Benchmark {
7382         namespace Detail {
7383             using sample = std::vector<double>;
7384
7385             double weighted_average_quantile(int k,
7386                                              int q,
7387                                              std::vector<double>::iterator first,
7388                                              std::vector<double>::iterator last);
7389
7390             template <typename Iterator>
7391             OutlierClassification classify_outliers(Iterator first, Iterator last) {
7392                 std::vector<double> copy(first, last);
7393
7394                 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
7395                 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
7396                 auto iqr = q3 - q1;
7397                 auto los = q1 - (iqr * 3.);
7398                 auto lom = q1 - (iqr * 1.5);
7399                 auto him = q3 + (iqr * 1.5);
7400                 auto his = q3 + (iqr * 3.);
7401
7402                 OutlierClassification o;
7403                 for (; first != last; ++first) {
7404                     auto&& t = *first;
7405                     if (t < los)
7406                         ++o.low_severe;
7407                     else if (t < lom)
7408                         ++o.low_mild;
7409                     else if (t > his)
7410                         ++o.high_severe;
7411                     else if (t > him)
7412                         ++o.high_mild;
7413                     ++o.samples_seen;
7414                 }
7415                 return o;
7416             }
7417
7418             template <typename Iterator> double mean(Iterator first, Iterator last) {
7419                 auto count = last - first;
7420                 double sum = std::accumulate(first, last, 0.);
7421                 return sum / count;
7422             }
7423
7424             template <typename URng, typename Iterator, typename Estimator>
7425             sample resample(
7426                 URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
7427                 auto n = last - first;
7428                 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7429
7430                 sample out;
7431                 out.reserve(resamples);
7432                 std::generate_n(
7433                     std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7434                         std::vector<double> resampled;
7435                         resampled.reserve(n);
7436                         std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] {
7437                             return first[dist(rng)];
7438                         });
7439                         return estimator(resampled.begin(), resampled.end());
7440                     });
7441                 std::sort(out.begin(), out.end());
7442                 return out;
7443             }
7444
7445             template <typename Estimator, typename Iterator>
7446             sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7447                 auto n = last - first;
7448                 auto second = std::next(first);
7449                 sample results;
7450                 results.reserve(n);
7451
7452                 for (auto it = first; it != last; ++it) {
7453                     std::iter_swap(it, first);
7454                     results.push_back(estimator(second, last));
7455                 }
7456
7457                 return results;
7458             }
7459
7460             inline double normal_cdf(double x) { return std::erfc(-x / std::sqrt(2.0)) / 2.0; }
7461
7462             double erfc_inv(double x);
7463
7464             double normal_quantile(double p);
7465
7466             template <typename Iterator, typename Estimator>
7467             Estimate<double> bootstrap(double confidence_level,
7468                                        Iterator first,
7469                                        Iterator last,
7470                                        sample const& resample,
7471                                        Estimator&& estimator) {
7472                 auto n_samples = last - first;
7473
7474                 double point = estimator(first, last);
7475                 // Degenerate case with a single sample
7476                 if (n_samples == 1)
7477                     return {point, point, point, confidence_level};
7478
7479                 sample jack = jackknife(estimator, first, last);
7480                 double jack_mean = mean(jack.begin(), jack.end());
7481                 double sum_squares, sum_cubes;
7482                 std::tie(sum_squares, sum_cubes) =
7483                     std::accumulate(jack.begin(),
7484                                     jack.end(),
7485                                     std::make_pair(0., 0.),
7486                                     [jack_mean](std::pair<double, double> sqcb,
7487                                                 double x) -> std::pair<double, double> {
7488                                         auto d = jack_mean - x;
7489                                         auto d2 = d * d;
7490                                         auto d3 = d2 * d;
7491                                         return {sqcb.first + d2, sqcb.second + d3};
7492                                     });
7493
7494                 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7495                 int n = static_cast<int>(resample.size());
7496                 double prob_n = std::count_if(resample.begin(),
7497                                               resample.end(),
7498                                               [point](double x) { return x < point; }) /
7499                                 (double)n;
7500                 // degenerate case with uniform samples
7501                 if (prob_n == 0)
7502                     return {point, point, point, confidence_level};
7503
7504                 double bias = normal_quantile(prob_n);
7505                 double z1 = normal_quantile((1. - confidence_level) / 2.);
7506
7507                 auto cumn = [n](double x) -> int { return std::lround(normal_cdf(x) * n); };
7508                 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7509                 double b1 = bias + z1;
7510                 double b2 = bias - z1;
7511                 double a1 = a(b1);
7512                 double a2 = a(b2);
7513                 auto lo = (std::max)(cumn(a1), 0);
7514                 auto hi = (std::min)(cumn(a2), n - 1);
7515
7516                 return {point, resample[lo], resample[hi], confidence_level};
7517             }
7518
7519             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7520
7521             struct bootstrap_analysis {
7522                 Estimate<double> mean;
7523                 Estimate<double> standard_deviation;
7524                 double outlier_variance;
7525             };
7526
7527             bootstrap_analysis analyse_samples(double confidence_level,
7528                                                int n_resamples,
7529                                                std::vector<double>::iterator first,
7530                                                std::vector<double>::iterator last);
7531         } // namespace Detail
7532     }     // namespace Benchmark
7533 } // namespace Catch
7534
7535 // end catch_stats.hpp
7536 #include <algorithm>
7537 #include <iterator>
7538 #include <tuple>
7539 #include <vector>
7540 #include <cmath>
7541
7542 namespace Catch {
7543     namespace Benchmark {
7544         namespace Detail {
7545             template <typename Clock> std::vector<double> resolution(int k) {
7546                 std::vector<TimePoint<Clock>> times;
7547                 times.reserve(k + 1);
7548                 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7549
7550                 std::vector<double> deltas;
7551                 deltas.reserve(k);
7552                 std::transform(std::next(times.begin()),
7553                                times.end(),
7554                                times.begin(),
7555                                std::back_inserter(deltas),
7556                                [](TimePoint<Clock> a, TimePoint<Clock> b) {
7557                                    return static_cast<double>((a - b).count());
7558                                });
7559
7560                 return deltas;
7561             }
7562
7563             const auto warmup_iterations = 10000;
7564             const auto warmup_time = std::chrono::milliseconds(100);
7565             const auto minimum_ticks = 1000;
7566             const auto warmup_seed = 10000;
7567             const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7568             const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7569             const auto clock_cost_estimation_tick_limit = 100000;
7570             const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7571             const auto clock_cost_estimation_iterations = 10000;
7572
7573             template <typename Clock> int warmup() {
7574                 return run_for_at_least<Clock>(
7575                            std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7576                            warmup_seed,
7577                            &resolution<Clock>)
7578                     .iterations;
7579             }
7580             template <typename Clock>
7581             EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7582                 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(
7583                                                      clock_resolution_estimation_time),
7584                                                  iterations,
7585                                                  &resolution<Clock>)
7586                              .result;
7587                 return {
7588                     FloatDuration<Clock>(mean(r.begin(), r.end())),
7589                     classify_outliers(r.begin(), r.end()),
7590                 };
7591             }
7592             template <typename Clock>
7593             EnvironmentEstimate<FloatDuration<Clock>>
7594             estimate_clock_cost(FloatDuration<Clock> resolution) {
7595                 auto time_limit =
7596                     (std::min)(resolution * clock_cost_estimation_tick_limit,
7597                                FloatDuration<Clock>(clock_cost_estimation_time_limit));
7598                 auto time_clock = [](int k) {
7599                     return Detail::measure<Clock>([k] {
7600                                for (int i = 0; i < k; ++i) {
7601                                    volatile auto ignored = Clock::now();
7602                                    (void)ignored;
7603                                }
7604                            })
7605                         .elapsed;
7606                 };
7607                 time_clock(1);
7608                 int iters = clock_cost_estimation_iterations;
7609                 auto&& r = run_for_at_least<Clock>(
7610                     std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time),
7611                     iters,
7612                     time_clock);
7613                 std::vector<double> times;
7614                 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7615                 times.reserve(nsamples);
7616                 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7617                     return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7618                 });
7619                 return {
7620                     FloatDuration<Clock>(mean(times.begin(), times.end())),
7621                     classify_outliers(times.begin(), times.end()),
7622                 };
7623             }
7624
7625             template <typename Clock> Environment<FloatDuration<Clock>> measure_environment() {
7626                 static Environment<FloatDuration<Clock>>* env = nullptr;
7627                 if (env) {
7628                     return *env;
7629                 }
7630
7631                 auto iters = Detail::warmup<Clock>();
7632                 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7633                 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7634
7635                 env = new Environment<FloatDuration<Clock>>{resolution, cost};
7636                 return *env;
7637             }
7638         } // namespace Detail
7639     }     // namespace Benchmark
7640 } // namespace Catch
7641
7642 // end catch_estimate_clock.hpp
7643 // start catch_analyse.hpp
7644
7645 // Run and analyse one benchmark
7646
7647 // start catch_sample_analysis.hpp
7648
7649 // Benchmark results
7650
7651 #include <algorithm>
7652 #include <vector>
7653 #include <string>
7654 #include <iterator>
7655
7656 namespace Catch {
7657     namespace Benchmark {
7658         template <typename Duration> struct SampleAnalysis {
7659             std::vector<Duration> samples;
7660             Estimate<Duration> mean;
7661             Estimate<Duration> standard_deviation;
7662             OutlierClassification outliers;
7663             double outlier_variance;
7664
7665             template <typename Duration2> operator SampleAnalysis<Duration2>() const {
7666                 std::vector<Duration2> samples2;
7667                 samples2.reserve(samples.size());
7668                 std::transform(samples.begin(),
7669                                samples.end(),
7670                                std::back_inserter(samples2),
7671                                [](Duration d) { return Duration2(d); });
7672                 return {
7673                     std::move(samples2),
7674                     mean,
7675                     standard_deviation,
7676                     outliers,
7677                     outlier_variance,
7678                 };
7679             }
7680         };
7681     } // namespace Benchmark
7682 } // namespace Catch
7683
7684 // end catch_sample_analysis.hpp
7685 #include <algorithm>
7686 #include <iterator>
7687 #include <vector>
7688
7689 namespace Catch {
7690     namespace Benchmark {
7691         namespace Detail {
7692             template <typename Duration, typename Iterator>
7693             SampleAnalysis<Duration>
7694             analyse(const IConfig& cfg, Environment<Duration>, Iterator first, Iterator last) {
7695                 if (!cfg.benchmarkNoAnalysis()) {
7696                     std::vector<double> samples;
7697                     samples.reserve(last - first);
7698                     std::transform(first, last, std::back_inserter(samples), [](Duration d) {
7699                         return d.count();
7700                     });
7701
7702                     auto analysis =
7703                         Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(),
7704                                                                   cfg.benchmarkResamples(),
7705                                                                   samples.begin(),
7706                                                                   samples.end());
7707                     auto outliers =
7708                         Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7709
7710                     auto wrap_estimate = [](Estimate<double> e) {
7711                         return Estimate<Duration>{
7712                             Duration(e.point),
7713                             Duration(e.lower_bound),
7714                             Duration(e.upper_bound),
7715                             e.confidence_interval,
7716                         };
7717                     };
7718                     std::vector<Duration> samples2;
7719                     samples2.reserve(samples.size());
7720                     std::transform(samples.begin(),
7721                                    samples.end(),
7722                                    std::back_inserter(samples2),
7723                                    [](double d) { return Duration(d); });
7724                     return {
7725                         std::move(samples2),
7726                         wrap_estimate(analysis.mean),
7727                         wrap_estimate(analysis.standard_deviation),
7728                         outliers,
7729                         analysis.outlier_variance,
7730                     };
7731                 } else {
7732                     std::vector<Duration> samples;
7733                     samples.reserve(last - first);
7734
7735                     Duration mean = Duration(0);
7736                     int i = 0;
7737                     for (auto it = first; it < last; ++it, ++i) {
7738                         samples.push_back(Duration(*it));
7739                         mean += Duration(*it);
7740                     }
7741                     mean /= i;
7742
7743                     return {std::move(samples),
7744                             Estimate<Duration>{mean, mean, mean, 0.0},
7745                             Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7746                             OutlierClassification{},
7747                             0.0};
7748                 }
7749             }
7750         } // namespace Detail
7751     }     // namespace Benchmark
7752 } // namespace Catch
7753
7754 // end catch_analyse.hpp
7755 #include <algorithm>
7756 #include <functional>
7757 #include <string>
7758 #include <vector>
7759 #include <cmath>
7760
7761 namespace Catch {
7762     namespace Benchmark {
7763         struct Benchmark {
7764             Benchmark(std::string&& name) : name(std::move(name)) {}
7765
7766             template <class FUN>
7767             Benchmark(std::string&& name, FUN&& func) :
7768                 fun(std::move(func)), name(std::move(name)) {}
7769
7770             template <typename Clock>
7771             ExecutionPlan<FloatDuration<Clock>>
7772             prepare(const IConfig& cfg, Environment<FloatDuration<Clock>> env) const {
7773                 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7774                 auto run_time = std::max(
7775                     min_time,
7776                     std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7777                 auto&& test = Detail::run_for_at_least<Clock>(
7778                     std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7779                 int new_iters =
7780                     static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7781                 return {new_iters,
7782                         test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(),
7783                         fun,
7784                         std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()),
7785                         Detail::warmup_iterations};
7786             }
7787
7788             template <typename Clock = default_clock> void run() {
7789                 IConfigPtr cfg = getCurrentContext().getConfig();
7790
7791                 auto env = Detail::measure_environment<Clock>();
7792
7793                 getResultCapture().benchmarkPreparing(name);
7794                 CATCH_TRY {
7795                     auto plan = user_code([&] { return prepare<Clock>(*cfg, env); });
7796
7797                     BenchmarkInfo info{name,
7798                                        plan.estimated_duration.count(),
7799                                        plan.iterations_per_sample,
7800                                        cfg->benchmarkSamples(),
7801                                        cfg->benchmarkResamples(),
7802                                        env.clock_resolution.mean.count(),
7803                                        env.clock_cost.mean.count()};
7804
7805                     getResultCapture().benchmarkStarting(info);
7806
7807                     auto samples = user_code([&] { return plan.template run<Clock>(*cfg, env); });
7808
7809                     auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7810                     BenchmarkStats<FloatDuration<Clock>> stats{info,
7811                                                                analysis.samples,
7812                                                                analysis.mean,
7813                                                                analysis.standard_deviation,
7814                                                                analysis.outliers,
7815                                                                analysis.outlier_variance};
7816                     getResultCapture().benchmarkEnded(stats);
7817                 }
7818                 CATCH_CATCH_ALL {
7819                     if (translateActiveException() !=
7820                         Detail::benchmarkErrorMsg) // benchmark errors have been
7821                                                    // reported, otherwise
7822                                                    // rethrow.
7823                         std::rethrow_exception(std::current_exception());
7824                 }
7825             }
7826
7827             // sets lambda to be used in fun *and* executes benchmark!
7828             template <
7829                 typename Fun,
7830                 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7831             Benchmark& operator=(Fun func) {
7832                 fun = Detail::BenchmarkFunction(func);
7833                 run();
7834                 return *this;
7835             }
7836
7837             explicit operator bool() { return true; }
7838
7839         private:
7840             Detail::BenchmarkFunction fun;
7841             std::string name;
7842         };
7843     } // namespace Benchmark
7844 } // namespace Catch
7845
7846 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7847 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7848
7849 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)                              \
7850     if (Catch::Benchmark::Benchmark BenchmarkName{name})                                           \
7851     BenchmarkName = [&](int benchmarkIndex)
7852
7853 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)                                     \
7854     if (Catch::Benchmark::Benchmark BenchmarkName{name})                                           \
7855     BenchmarkName = [&]
7856
7857 // end catch_benchmark.hpp
7858 // start catch_constructor.hpp
7859
7860 // Constructor and destructor helpers
7861
7862 #include <type_traits>
7863
7864 namespace Catch {
7865     namespace Benchmark {
7866         namespace Detail {
7867             template <typename T, bool Destruct> struct ObjectStorage {
7868                 using TStorage =
7869                     typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7870
7871                 ObjectStorage() : data() {}
7872
7873                 ObjectStorage(const ObjectStorage& other) { new (&data) T(other.stored_object()); }
7874
7875                 ObjectStorage(ObjectStorage&& other) {
7876                     new (&data) T(std::move(other.stored_object()));
7877                 }
7878
7879                 ~ObjectStorage() { destruct_on_exit<T>(); }
7880
7881                 template <typename... Args> void construct(Args&&... args) {
7882                     new (&data) T(std::forward<Args>(args)...);
7883                 }
7884
7885                 template <bool AllowManualDestruction = !Destruct>
7886                 typename std::enable_if<AllowManualDestruction>::type destruct() {
7887                     stored_object().~T();
7888                 }
7889
7890             private:
7891                 // If this is a constructor benchmark, destruct the underlying
7892                 // object
7893                 template <typename U>
7894                 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) {
7895                     destruct<true>();
7896                 }
7897                 // Otherwise, don't
7898                 template <typename U>
7899                 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) {}
7900
7901                 T& stored_object() { return *static_cast<T*>(static_cast<void*>(&data)); }
7902
7903                 T const& stored_object() const {
7904                     return *static_cast<T*>(static_cast<void*>(&data));
7905                 }
7906
7907                 TStorage data;
7908             };
7909         } // namespace Detail
7910
7911         template <typename T> using storage_for = Detail::ObjectStorage<T, true>;
7912
7913         template <typename T> using destructable_object = Detail::ObjectStorage<T, false>;
7914     } // namespace Benchmark
7915 } // namespace Catch
7916
7917 // end catch_constructor.hpp
7918 // end catch_benchmarking_all.hpp
7919 #endif
7920
7921 #endif // ! CATCH_CONFIG_IMPL_ONLY
7922
7923 #ifdef CATCH_IMPL
7924 // start catch_impl.hpp
7925
7926 #ifdef __clang__
7927 #pragma clang diagnostic push
7928 #pragma clang diagnostic ignored "-Wweak-vtables"
7929 #endif
7930
7931 // Keep these here for external reporters
7932 // start catch_test_case_tracker.h
7933
7934 #include <string>
7935 #include <vector>
7936 #include <memory>
7937
7938 namespace Catch {
7939     namespace TestCaseTracking {
7940
7941         struct NameAndLocation {
7942             std::string name;
7943             SourceLineInfo location;
7944
7945             NameAndLocation(std::string const& _name, SourceLineInfo const& _location);
7946             friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7947                 return lhs.name == rhs.name && lhs.location == rhs.location;
7948             }
7949         };
7950
7951         class ITracker;
7952
7953         using ITrackerPtr = std::shared_ptr<ITracker>;
7954
7955         class ITracker {
7956             NameAndLocation m_nameAndLocation;
7957
7958         public:
7959             ITracker(NameAndLocation const& nameAndLoc) : m_nameAndLocation(nameAndLoc) {}
7960
7961             // static queries
7962             NameAndLocation const& nameAndLocation() const { return m_nameAndLocation; }
7963
7964             virtual ~ITracker();
7965
7966             // dynamic queries
7967             virtual bool isComplete() const = 0; // Successfully completed or failed
7968             virtual bool isSuccessfullyCompleted() const = 0;
7969             virtual bool isOpen() const = 0; // Started but not complete
7970             virtual bool hasChildren() const = 0;
7971             virtual bool hasStarted() const = 0;
7972
7973             virtual ITracker& parent() = 0;
7974
7975             // actions
7976             virtual void close() = 0; // Successfully complete
7977             virtual void fail() = 0;
7978             virtual void markAsNeedingAnotherRun() = 0;
7979
7980             virtual void addChild(ITrackerPtr const& child) = 0;
7981             virtual ITrackerPtr findChild(NameAndLocation const& nameAndLocation) = 0;
7982             virtual void openChild() = 0;
7983
7984             // Debug/ checking
7985             virtual bool isSectionTracker() const = 0;
7986             virtual bool isGeneratorTracker() const = 0;
7987         };
7988
7989         class TrackerContext {
7990
7991             enum RunState { NotStarted, Executing, CompletedCycle };
7992
7993             ITrackerPtr m_rootTracker;
7994             ITracker* m_currentTracker = nullptr;
7995             RunState m_runState = NotStarted;
7996
7997         public:
7998             ITracker& startRun();
7999             void endRun();
8000
8001             void startCycle();
8002             void completeCycle();
8003
8004             bool completedCycle() const;
8005             ITracker& currentTracker();
8006             void setCurrentTracker(ITracker* tracker);
8007         };
8008
8009         class TrackerBase : public ITracker {
8010         protected:
8011             enum CycleState {
8012                 NotStarted,
8013                 Executing,
8014                 ExecutingChildren,
8015                 NeedsAnotherRun,
8016                 CompletedSuccessfully,
8017                 Failed
8018             };
8019
8020             using Children = std::vector<ITrackerPtr>;
8021             TrackerContext& m_ctx;
8022             ITracker* m_parent;
8023             Children m_children;
8024             CycleState m_runState = NotStarted;
8025
8026         public:
8027             TrackerBase(NameAndLocation const& nameAndLocation,
8028                         TrackerContext& ctx,
8029                         ITracker* parent);
8030
8031             bool isComplete() const override;
8032             bool isSuccessfullyCompleted() const override;
8033             bool isOpen() const override;
8034             bool hasChildren() const override;
8035             bool hasStarted() const override { return m_runState != NotStarted; }
8036
8037             void addChild(ITrackerPtr const& child) override;
8038
8039             ITrackerPtr findChild(NameAndLocation const& nameAndLocation) override;
8040             ITracker& parent() override;
8041
8042             void openChild() override;
8043
8044             bool isSectionTracker() const override;
8045             bool isGeneratorTracker() const override;
8046
8047             void open();
8048
8049             void close() override;
8050             void fail() override;
8051             void markAsNeedingAnotherRun() override;
8052
8053         private:
8054             void moveToParent();
8055             void moveToThis();
8056         };
8057
8058         class SectionTracker : public TrackerBase {
8059             std::vector<std::string> m_filters;
8060             std::string m_trimmed_name;
8061
8062         public:
8063             SectionTracker(NameAndLocation const& nameAndLocation,
8064                            TrackerContext& ctx,
8065                            ITracker* parent);
8066
8067             bool isSectionTracker() const override;
8068
8069             bool isComplete() const override;
8070
8071             static SectionTracker& acquire(TrackerContext& ctx,
8072                                            NameAndLocation const& nameAndLocation);
8073
8074             void tryOpen();
8075
8076             void addInitialFilters(std::vector<std::string> const& filters);
8077             void addNextFilters(std::vector<std::string> const& filters);
8078             //! Returns filters active in this tracker
8079             std::vector<std::string> const& getFilters() const;
8080             //! Returns whitespace-trimmed name of the tracked section
8081             std::string const& trimmedName() const;
8082         };
8083
8084     } // namespace TestCaseTracking
8085
8086     using TestCaseTracking::ITracker;
8087     using TestCaseTracking::SectionTracker;
8088     using TestCaseTracking::TrackerContext;
8089
8090 } // namespace Catch
8091
8092 // end catch_test_case_tracker.h
8093
8094 // start catch_leak_detector.h
8095
8096 namespace Catch {
8097
8098     struct LeakDetector {
8099         LeakDetector();
8100         ~LeakDetector();
8101     };
8102
8103 } // namespace Catch
8104 // end catch_leak_detector.h
8105 // Cpp files will be included in the single-header file here
8106 // start catch_stats.cpp
8107
8108 // Statistical analysis tools
8109
8110 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8111
8112 #include <cassert>
8113 #include <random>
8114
8115 #if defined(CATCH_CONFIG_USE_ASYNC)
8116 #include <future>
8117 #endif
8118
8119 namespace {
8120     double erf_inv(double x) {
8121         // Code accompanying the article "Approximating the erfinv function" in
8122         // GPU Computing Gems, Volume 2
8123         double w, p;
8124
8125         w = -log((1.0 - x) * (1.0 + x));
8126
8127         if (w < 6.250000) {
8128             w = w - 3.125000;
8129             p = -3.6444120640178196996e-21;
8130             p = -1.685059138182016589e-19 + p * w;
8131             p = 1.2858480715256400167e-18 + p * w;
8132             p = 1.115787767802518096e-17 + p * w;
8133             p = -1.333171662854620906e-16 + p * w;
8134             p = 2.0972767875968561637e-17 + p * w;
8135             p = 6.6376381343583238325e-15 + p * w;
8136             p = -4.0545662729752068639e-14 + p * w;
8137             p = -8.1519341976054721522e-14 + p * w;
8138             p = 2.6335093153082322977e-12 + p * w;
8139             p = -1.2975133253453532498e-11 + p * w;
8140             p = -5.4154120542946279317e-11 + p * w;
8141             p = 1.051212273321532285e-09 + p * w;
8142             p = -4.1126339803469836976e-09 + p * w;
8143             p = -2.9070369957882005086e-08 + p * w;
8144             p = 4.2347877827932403518e-07 + p * w;
8145             p = -1.3654692000834678645e-06 + p * w;
8146             p = -1.3882523362786468719e-05 + p * w;
8147             p = 0.0001867342080340571352 + p * w;
8148             p = -0.00074070253416626697512 + p * w;
8149             p = -0.0060336708714301490533 + p * w;
8150             p = 0.24015818242558961693 + p * w;
8151             p = 1.6536545626831027356 + p * w;
8152         } else if (w < 16.000000) {
8153             w = sqrt(w) - 3.250000;
8154             p = 2.2137376921775787049e-09;
8155             p = 9.0756561938885390979e-08 + p * w;
8156             p = -2.7517406297064545428e-07 + p * w;
8157             p = 1.8239629214389227755e-08 + p * w;
8158             p = 1.5027403968909827627e-06 + p * w;
8159             p = -4.013867526981545969e-06 + p * w;
8160             p = 2.9234449089955446044e-06 + p * w;
8161             p = 1.2475304481671778723e-05 + p * w;
8162             p = -4.7318229009055733981e-05 + p * w;
8163             p = 6.8284851459573175448e-05 + p * w;
8164             p = 2.4031110387097893999e-05 + p * w;
8165             p = -0.0003550375203628474796 + p * w;
8166             p = 0.00095328937973738049703 + p * w;
8167             p = -0.0016882755560235047313 + p * w;
8168             p = 0.0024914420961078508066 + p * w;
8169             p = -0.0037512085075692412107 + p * w;
8170             p = 0.005370914553590063617 + p * w;
8171             p = 1.0052589676941592334 + p * w;
8172             p = 3.0838856104922207635 + p * w;
8173         } else {
8174             w = sqrt(w) - 5.000000;
8175             p = -2.7109920616438573243e-11;
8176             p = -2.5556418169965252055e-10 + p * w;
8177             p = 1.5076572693500548083e-09 + p * w;
8178             p = -3.7894654401267369937e-09 + p * w;
8179             p = 7.6157012080783393804e-09 + p * w;
8180             p = -1.4960026627149240478e-08 + p * w;
8181             p = 2.9147953450901080826e-08 + p * w;
8182             p = -6.7711997758452339498e-08 + p * w;
8183             p = 2.2900482228026654717e-07 + p * w;
8184             p = -9.9298272942317002539e-07 + p * w;
8185             p = 4.5260625972231537039e-06 + p * w;
8186             p = -1.9681778105531670567e-05 + p * w;
8187             p = 7.5995277030017761139e-05 + p * w;
8188             p = -0.00021503011930044477347 + p * w;
8189             p = -0.00013871931833623122026 + p * w;
8190             p = 1.0103004648645343977 + p * w;
8191             p = 4.8499064014085844221 + p * w;
8192         }
8193         return p * x;
8194     }
8195
8196     double standard_deviation(std::vector<double>::iterator first,
8197                               std::vector<double>::iterator last) {
8198         auto m = Catch::Benchmark::Detail::mean(first, last);
8199         double variance = std::accumulate(first,
8200                                           last,
8201                                           0.,
8202                                           [m](double a, double b) {
8203                                               double diff = b - m;
8204                                               return a + diff * diff;
8205                                           }) /
8206                           (last - first);
8207         return std::sqrt(variance);
8208     }
8209
8210 } // namespace
8211
8212 namespace Catch {
8213     namespace Benchmark {
8214         namespace Detail {
8215
8216             double weighted_average_quantile(int k,
8217                                              int q,
8218                                              std::vector<double>::iterator first,
8219                                              std::vector<double>::iterator last) {
8220                 auto count = last - first;
8221                 double idx = (count - 1) * k / static_cast<double>(q);
8222                 int j = static_cast<int>(idx);
8223                 double g = idx - j;
8224                 std::nth_element(first, first + j, last);
8225                 auto xj = first[j];
8226                 if (g == 0)
8227                     return xj;
8228
8229                 auto xj1 = *std::min_element(first + (j + 1), last);
8230                 return xj + g * (xj1 - xj);
8231             }
8232
8233             double erfc_inv(double x) { return erf_inv(1.0 - x); }
8234
8235             double normal_quantile(double p) {
8236                 static const double ROOT_TWO = std::sqrt(2.0);
8237
8238                 double result = 0.0;
8239                 assert(p >= 0 && p <= 1);
8240                 if (p < 0 || p > 1) {
8241                     return result;
8242                 }
8243
8244                 result = -erfc_inv(2.0 * p);
8245                 // result *= normal distribution standard deviation (1.0) *
8246                 // sqrt(2)
8247                 result *= /*sd * */ ROOT_TWO;
8248                 // result += normal disttribution mean (0)
8249                 return result;
8250             }
8251
8252             double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
8253                 double sb = stddev.point;
8254                 double mn = mean.point / n;
8255                 double mg_min = mn / 2.;
8256                 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
8257                 double sg2 = sg * sg;
8258                 double sb2 = sb * sb;
8259
8260                 auto c_max = [n, mn, sb2, sg2](double x) -> double {
8261                     double k = mn - x;
8262                     double d = k * k;
8263                     double nd = n * d;
8264                     double k0 = -n * nd;
8265                     double k1 = sb2 - n * sg2 + nd;
8266                     double det = k1 * k1 - 4 * sg2 * k0;
8267                     return (int)(-2. * k0 / (k1 + std::sqrt(det)));
8268                 };
8269
8270                 auto var_out = [n, sb2, sg2](double c) {
8271                     double nc = n - c;
8272                     return (nc / n) * (sb2 - nc * sg2);
8273                 };
8274
8275                 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
8276             }
8277
8278             bootstrap_analysis analyse_samples(double confidence_level,
8279                                                int n_resamples,
8280                                                std::vector<double>::iterator first,
8281                                                std::vector<double>::iterator last) {
8282                 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
8283                 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
8284                 static std::random_device entropy;
8285                 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
8286
8287                 auto n = static_cast<int>(last - first); // seriously, one can't use integral types
8288                                                          // without hell in C++
8289
8290                 auto mean = &Detail::mean<std::vector<double>::iterator>;
8291                 auto stddev = &standard_deviation;
8292
8293 #if defined(CATCH_CONFIG_USE_ASYNC)
8294                 auto Estimate =
8295                     [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8296                         auto seed = entropy();
8297                         return std::async(std::launch::async, [=] {
8298                             std::mt19937 rng(seed);
8299                             auto resampled = resample(rng, n_resamples, first, last, f);
8300                             return bootstrap(confidence_level, first, last, resampled, f);
8301                         });
8302                     };
8303
8304                 auto mean_future = Estimate(mean);
8305                 auto stddev_future = Estimate(stddev);
8306
8307                 auto mean_estimate = mean_future.get();
8308                 auto stddev_estimate = stddev_future.get();
8309 #else
8310                 auto Estimate =
8311                     [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
8312                         auto seed = entropy();
8313                         std::mt19937 rng(seed);
8314                         auto resampled = resample(rng, n_resamples, first, last, f);
8315                         return bootstrap(confidence_level, first, last, resampled, f);
8316                     };
8317
8318                 auto mean_estimate = Estimate(mean);
8319                 auto stddev_estimate = Estimate(stddev);
8320 #endif // CATCH_USE_ASYNC
8321
8322                 double outlier_variance =
8323                     Detail::outlier_variance(mean_estimate, stddev_estimate, n);
8324
8325                 return {mean_estimate, stddev_estimate, outlier_variance};
8326             }
8327         } // namespace Detail
8328     }     // namespace Benchmark
8329 } // namespace Catch
8330
8331 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8332 // end catch_stats.cpp
8333 // start catch_approx.cpp
8334
8335 #include <cmath>
8336 #include <limits>
8337
8338 namespace {
8339
8340     // Performs equivalent check of std::fabs(lhs - rhs) <= margin
8341     // But without the subtraction to allow for INFINITY in comparison
8342     bool marginComparison(double lhs, double rhs, double margin) {
8343         return (lhs + margin >= rhs) && (rhs + margin >= lhs);
8344     }
8345
8346 } // namespace
8347
8348 namespace Catch {
8349     namespace Detail {
8350
8351         Approx::Approx(double value) :
8352             m_epsilon(std::numeric_limits<float>::epsilon() * 100),
8353             m_margin(0.0),
8354             m_scale(0.0),
8355             m_value(value) {}
8356
8357         Approx Approx::custom() { return Approx(0); }
8358
8359         Approx Approx::operator-() const {
8360             auto temp(*this);
8361             temp.m_value = -temp.m_value;
8362             return temp;
8363         }
8364
8365         std::string Approx::toString() const {
8366             ReusableStringStream rss;
8367             rss << "Approx( " << ::Catch::Detail::stringify(m_value) << " )";
8368             return rss.str();
8369         }
8370
8371         bool Approx::equalityComparisonImpl(const double other) const {
8372             // First try with fixed margin, then compute margin based on
8373             // epsilon, scale and Approx's value Thanks to Richard Harris for
8374             // his help refining the scaled margin value
8375             return marginComparison(m_value, other, m_margin) ||
8376                    marginComparison(m_value,
8377                                     other,
8378                                     m_epsilon *
8379                                         (m_scale + std::fabs(std::isinf(m_value) ? 0 : m_value)));
8380         }
8381
8382         void Approx::setMargin(double newMargin) {
8383             CATCH_ENFORCE(newMargin >= 0,
8384                           "Invalid Approx::margin: " << newMargin << '.'
8385                                                      << " Approx::Margin has to be non-negative.");
8386             m_margin = newMargin;
8387         }
8388
8389         void Approx::setEpsilon(double newEpsilon) {
8390             CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
8391                           "Invalid Approx::epsilon: " << newEpsilon << '.'
8392                                                       << " Approx::epsilon has to be in [0, 1]");
8393             m_epsilon = newEpsilon;
8394         }
8395
8396     } // end namespace Detail
8397
8398     namespace literals {
8399         Detail::Approx operator"" _a(long double val) { return Detail::Approx(val); }
8400         Detail::Approx operator"" _a(unsigned long long val) { return Detail::Approx(val); }
8401     } // end namespace literals
8402
8403     std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
8404         return value.toString();
8405     }
8406
8407 } // end namespace Catch
8408 // end catch_approx.cpp
8409 // start catch_assertionhandler.cpp
8410
8411 // start catch_debugger.h
8412
8413 namespace Catch {
8414     bool isDebuggerActive();
8415 }
8416
8417 #ifdef CATCH_PLATFORM_MAC
8418
8419 #if defined(__i386__) || defined(__x86_64__)
8420 #define CATCH_TRAP() __asm__("int $3\n" : :) /* NOLINT */
8421 #elif defined(__aarch64__)
8422 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8423 #endif
8424
8425 #elif defined(CATCH_PLATFORM_IPHONE)
8426
8427 // use inline assembler
8428 #if defined(__i386__) || defined(__x86_64__)
8429 #define CATCH_TRAP() __asm__("int $3")
8430 #elif defined(__aarch64__)
8431 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
8432 #elif defined(__arm__) && !defined(__thumb__)
8433 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8434 #elif defined(__arm__) && defined(__thumb__)
8435 #define CATCH_TRAP() __asm__(".inst 0xde01")
8436 #endif
8437
8438 #elif defined(CATCH_PLATFORM_LINUX)
8439 // If we can use inline assembler, do it because this allows us to break
8440 // directly at the location of the failing check instead of breaking inside
8441 // raise() called from it, i.e. one stack frame below.
8442 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8443 #define CATCH_TRAP() asm volatile("int $3") /* NOLINT */
8444 #else                                       // Fall back to the generic way.
8445 #include <signal.h>
8446
8447 #define CATCH_TRAP() raise(SIGTRAP)
8448 #endif
8449 #elif defined(_MSC_VER)
8450 #define CATCH_TRAP() __debugbreak()
8451 #elif defined(__MINGW32__)
8452 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
8453 #define CATCH_TRAP() DebugBreak()
8454 #endif
8455
8456 #ifndef CATCH_BREAK_INTO_DEBUGGER
8457 #ifdef CATCH_TRAP
8458 #define CATCH_BREAK_INTO_DEBUGGER()                                                                \
8459     [] {                                                                                           \
8460         if (Catch::isDebuggerActive()) {                                                           \
8461             CATCH_TRAP();                                                                          \
8462         }                                                                                          \
8463     }()
8464 #else
8465 #define CATCH_BREAK_INTO_DEBUGGER() [] {}()
8466 #endif
8467 #endif
8468
8469 // end catch_debugger.h
8470 // start catch_run_context.h
8471
8472 // start catch_fatal_condition.h
8473
8474 #include <cassert>
8475
8476 namespace Catch {
8477
8478     // Wrapper for platform-specific fatal error (signals/SEH) handlers
8479     //
8480     // Tries to be cooperative with other handlers, and not step over
8481     // other handlers. This means that unknown structured exceptions
8482     // are passed on, previous signal handlers are called, and so on.
8483     //
8484     // Can only be instantiated once, and assumes that once a signal
8485     // is caught, the binary will end up terminating. Thus, there
8486     class FatalConditionHandler {
8487         bool m_started = false;
8488
8489         // Install/disengage implementation for specific platform.
8490         // Should be if-defed to work on current platform, can assume
8491         // engage-disengage 1:1 pairing.
8492         void engage_platform();
8493         void disengage_platform();
8494
8495     public:
8496         // Should also have platform-specific implementations as needed
8497         FatalConditionHandler();
8498         ~FatalConditionHandler();
8499
8500         void engage() {
8501             assert(!m_started && "Handler cannot be installed twice.");
8502             m_started = true;
8503             engage_platform();
8504         }
8505
8506         void disengage() {
8507             assert(m_started && "Handler cannot be uninstalled without being installed first");
8508             m_started = false;
8509             disengage_platform();
8510         }
8511     };
8512
8513     //! Simple RAII guard for (dis)engaging the FatalConditionHandler
8514     class FatalConditionHandlerGuard {
8515         FatalConditionHandler* m_handler;
8516
8517     public:
8518         FatalConditionHandlerGuard(FatalConditionHandler* handler) : m_handler(handler) {
8519             m_handler->engage();
8520         }
8521         ~FatalConditionHandlerGuard() { m_handler->disengage(); }
8522     };
8523
8524 } // end namespace Catch
8525
8526 // end catch_fatal_condition.h
8527 #include <string>
8528
8529 namespace Catch {
8530
8531     struct IMutableContext;
8532
8533     ///////////////////////////////////////////////////////////////////////////
8534
8535     class RunContext : public IResultCapture, public IRunner {
8536
8537     public:
8538         RunContext(RunContext const&) = delete;
8539         RunContext& operator=(RunContext const&) = delete;
8540
8541         explicit RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter);
8542
8543         ~RunContext() override;
8544
8545         void testGroupStarting(std::string const& testSpec,
8546                                std::size_t groupIndex,
8547                                std::size_t groupsCount);
8548         void testGroupEnded(std::string const& testSpec,
8549                             Totals const& totals,
8550                             std::size_t groupIndex,
8551                             std::size_t groupsCount);
8552
8553         Totals runTest(TestCase const& testCase);
8554
8555         IConfigPtr config() const;
8556         IStreamingReporter& reporter() const;
8557
8558     public: // IResultCapture
8559         // Assertion handlers
8560         void handleExpr(AssertionInfo const& info,
8561                         ITransientExpression const& expr,
8562                         AssertionReaction& reaction) override;
8563         void handleMessage(AssertionInfo const& info,
8564                            ResultWas::OfType resultType,
8565                            StringRef const& message,
8566                            AssertionReaction& reaction) override;
8567         void handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
8568                                                 AssertionReaction& reaction) override;
8569         void handleUnexpectedInflightException(AssertionInfo const& info,
8570                                                std::string const& message,
8571                                                AssertionReaction& reaction) override;
8572         void handleIncomplete(AssertionInfo const& info) override;
8573         void handleNonExpr(AssertionInfo const& info,
8574                            ResultWas::OfType resultType,
8575                            AssertionReaction& reaction) override;
8576
8577         bool sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) override;
8578
8579         void sectionEnded(SectionEndInfo const& endInfo) override;
8580         void sectionEndedEarly(SectionEndInfo const& endInfo) override;
8581
8582         auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
8583             -> IGeneratorTracker& override;
8584
8585 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8586         void benchmarkPreparing(std::string const& name) override;
8587         void benchmarkStarting(BenchmarkInfo const& info) override;
8588         void benchmarkEnded(BenchmarkStats<> const& stats) override;
8589         void benchmarkFailed(std::string const& error) override;
8590 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8591
8592         void pushScopedMessage(MessageInfo const& message) override;
8593         void popScopedMessage(MessageInfo const& message) override;
8594
8595         void emplaceUnscopedMessage(MessageBuilder const& builder) override;
8596
8597         std::string getCurrentTestName() const override;
8598
8599         const AssertionResult* getLastResult() const override;
8600
8601         void exceptionEarlyReported() override;
8602
8603         void handleFatalErrorCondition(StringRef message) override;
8604
8605         bool lastAssertionPassed() override;
8606
8607         void assertionPassed() override;
8608
8609     public:
8610         // !TBD We need to do this another way!
8611         bool aborting() const final;
8612
8613     private:
8614         void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr);
8615         void invokeActiveTestCase();
8616
8617         void resetAssertionInfo();
8618         bool testForMissingAssertions(Counts& assertions);
8619
8620         void assertionEnded(AssertionResult const& result);
8621         void reportExpr(AssertionInfo const& info,
8622                         ResultWas::OfType resultType,
8623                         ITransientExpression const* expr,
8624                         bool negated);
8625
8626         void populateReaction(AssertionReaction& reaction);
8627
8628     private:
8629         void handleUnfinishedSections();
8630
8631         TestRunInfo m_runInfo;
8632         IMutableContext& m_context;
8633         TestCase const* m_activeTestCase = nullptr;
8634         ITracker* m_testCaseTracker = nullptr;
8635         Option<AssertionResult> m_lastResult;
8636
8637         IConfigPtr m_config;
8638         Totals m_totals;
8639         IStreamingReporterPtr m_reporter;
8640         std::vector<MessageInfo> m_messages;
8641         std::vector<ScopedMessage>
8642             m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8643         AssertionInfo m_lastAssertionInfo;
8644         std::vector<SectionEndInfo> m_unfinishedSections;
8645         std::vector<ITracker*> m_activeSections;
8646         TrackerContext m_trackerContext;
8647         FatalConditionHandler m_fatalConditionhandler;
8648         bool m_lastAssertionPassed = false;
8649         bool m_shouldReportUnexpected = true;
8650         bool m_includeSuccessfulResults;
8651     };
8652
8653     void seedRng(IConfig const& config);
8654     unsigned int rngSeed();
8655 } // end namespace Catch
8656
8657 // end catch_run_context.h
8658 namespace Catch {
8659
8660     namespace {
8661         auto operator<<(std::ostream& os, ITransientExpression const& expr) -> std::ostream& {
8662             expr.streamReconstructedExpression(os);
8663             return os;
8664         }
8665     } // namespace
8666
8667     LazyExpression::LazyExpression(bool isNegated) : m_isNegated(isNegated) {}
8668
8669     LazyExpression::LazyExpression(LazyExpression const& other) : m_isNegated(other.m_isNegated) {}
8670
8671     LazyExpression::operator bool() const { return m_transientExpression != nullptr; }
8672
8673     auto operator<<(std::ostream& os, LazyExpression const& lazyExpr) -> std::ostream& {
8674         if (lazyExpr.m_isNegated)
8675             os << "!";
8676
8677         if (lazyExpr) {
8678             if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
8679                 os << "(" << *lazyExpr.m_transientExpression << ")";
8680             else
8681                 os << *lazyExpr.m_transientExpression;
8682         } else {
8683             os << "{** error - unchecked empty expression requested **}";
8684         }
8685         return os;
8686     }
8687
8688     AssertionHandler::AssertionHandler(StringRef const& macroName,
8689                                        SourceLineInfo const& lineInfo,
8690                                        StringRef capturedExpression,
8691                                        ResultDisposition::Flags resultDisposition) :
8692         m_assertionInfo{macroName, lineInfo, capturedExpression, resultDisposition},
8693         m_resultCapture(getResultCapture()) {}
8694
8695     void AssertionHandler::handleExpr(ITransientExpression const& expr) {
8696         m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction);
8697     }
8698     void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8699         m_resultCapture.handleMessage(m_assertionInfo, resultType, message, m_reaction);
8700     }
8701
8702     auto AssertionHandler::allowThrows() const -> bool {
8703         return getCurrentContext().getConfig()->allowThrows();
8704     }
8705
8706     void AssertionHandler::complete() {
8707         setCompleted();
8708         if (m_reaction.shouldDebugBreak) {
8709
8710             // If you find your debugger stopping you here then go one level up
8711             // on the call-stack for the code that caused it (typically a failed
8712             // assertion)
8713
8714             // (To go back to the test and change execution, jump over the
8715             // throw, next)
8716             CATCH_BREAK_INTO_DEBUGGER();
8717         }
8718         if (m_reaction.shouldThrow) {
8719 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8720             throw Catch::TestFailureException();
8721 #else
8722             CATCH_ERROR("Test failure requires aborting test!");
8723 #endif
8724         }
8725     }
8726     void AssertionHandler::setCompleted() { m_completed = true; }
8727
8728     void AssertionHandler::handleUnexpectedInflightException() {
8729         m_resultCapture.handleUnexpectedInflightException(
8730             m_assertionInfo, Catch::translateActiveException(), m_reaction);
8731     }
8732
8733     void AssertionHandler::handleExceptionThrownAsExpected() {
8734         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8735     }
8736     void AssertionHandler::handleExceptionNotThrownAsExpected() {
8737         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8738     }
8739
8740     void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8741         m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, m_reaction);
8742     }
8743
8744     void AssertionHandler::handleThrowingCallSkipped() {
8745         m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8746     }
8747
8748     // This is the overload that takes a string and infers the Equals matcher
8749     // from it The more general overload, that takes any string matcher, is in
8750     // catch_capture_matchers.cpp
8751     void handleExceptionMatchExpr(AssertionHandler& handler,
8752                                   std::string const& str,
8753                                   StringRef const& matcherString) {
8754         handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString);
8755     }
8756
8757 } // namespace Catch
8758 // end catch_assertionhandler.cpp
8759 // start catch_assertionresult.cpp
8760
8761 namespace Catch {
8762     AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
8763                                              LazyExpression const& _lazyExpression) :
8764         lazyExpression(_lazyExpression), resultType(_resultType) {}
8765
8766     std::string AssertionResultData::reconstructExpression() const {
8767
8768         if (reconstructedExpression.empty()) {
8769             if (lazyExpression) {
8770                 ReusableStringStream rss;
8771                 rss << lazyExpression;
8772                 reconstructedExpression = rss.str();
8773             }
8774         }
8775         return reconstructedExpression;
8776     }
8777
8778     AssertionResult::AssertionResult(AssertionInfo const& info, AssertionResultData const& data) :
8779         m_info(info), m_resultData(data) {}
8780
8781     // Result was a success
8782     bool AssertionResult::succeeded() const { return Catch::isOk(m_resultData.resultType); }
8783
8784     // Result was a success, or failure is suppressed
8785     bool AssertionResult::isOk() const {
8786         return Catch::isOk(m_resultData.resultType) ||
8787                shouldSuppressFailure(m_info.resultDisposition);
8788     }
8789
8790     ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; }
8791
8792     bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); }
8793
8794     bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); }
8795
8796     std::string AssertionResult::getExpression() const {
8797         // Possibly overallocating by 3 characters should be basically free
8798         std::string expr;
8799         expr.reserve(m_info.capturedExpression.size() + 3);
8800         if (isFalseTest(m_info.resultDisposition)) {
8801             expr += "!(";
8802         }
8803         expr += m_info.capturedExpression;
8804         if (isFalseTest(m_info.resultDisposition)) {
8805             expr += ')';
8806         }
8807         return expr;
8808     }
8809
8810     std::string AssertionResult::getExpressionInMacro() const {
8811         std::string expr;
8812         if (m_info.macroName.empty())
8813             expr = static_cast<std::string>(m_info.capturedExpression);
8814         else {
8815             expr.reserve(m_info.macroName.size() + m_info.capturedExpression.size() + 4);
8816             expr += m_info.macroName;
8817             expr += "( ";
8818             expr += m_info.capturedExpression;
8819             expr += " )";
8820         }
8821         return expr;
8822     }
8823
8824     bool AssertionResult::hasExpandedExpression() const {
8825         return hasExpression() && getExpandedExpression() != getExpression();
8826     }
8827
8828     std::string AssertionResult::getExpandedExpression() const {
8829         std::string expr = m_resultData.reconstructExpression();
8830         return expr.empty() ? getExpression() : expr;
8831     }
8832
8833     std::string AssertionResult::getMessage() const { return m_resultData.message; }
8834     SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; }
8835
8836     StringRef AssertionResult::getTestMacroName() const { return m_info.macroName; }
8837
8838 } // end namespace Catch
8839 // end catch_assertionresult.cpp
8840 // start catch_capture_matchers.cpp
8841
8842 namespace Catch {
8843
8844     using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8845
8846     // This is the general overload that takes a any string matcher
8847     // There is another overload, in catch_assertionhandler.h/.cpp, that only
8848     // takes a string and infers the Equals matcher (so the header does not
8849     // mention matchers)
8850     void handleExceptionMatchExpr(AssertionHandler& handler,
8851                                   StringMatcher const& matcher,
8852                                   StringRef const& matcherString) {
8853         std::string exceptionMessage = Catch::translateActiveException();
8854         MatchExpr<std::string, StringMatcher const&> expr(exceptionMessage, matcher, matcherString);
8855         handler.handleExpr(expr);
8856     }
8857
8858 } // namespace Catch
8859 // end catch_capture_matchers.cpp
8860 // start catch_commandline.cpp
8861
8862 // start catch_commandline.h
8863
8864 // start catch_clara.h
8865
8866 // Use Catch's value for console width (store Clara's off to the side, if
8867 // present)
8868 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8869 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8870 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8871 #endif
8872 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1
8873
8874 #ifdef __clang__
8875 #pragma clang diagnostic push
8876 #pragma clang diagnostic ignored "-Wweak-vtables"
8877 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8878 #pragma clang diagnostic ignored "-Wshadow"
8879 #endif
8880
8881 // start clara.hpp
8882 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8883 //
8884 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8885 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8886 //
8887 // See https://github.com/philsquared/Clara for more details
8888
8889 // Clara v1.1.5
8890
8891 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8892 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8893 #endif
8894
8895 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8896 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8897 #endif
8898
8899 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8900 #ifdef __has_include
8901 #if __has_include(<optional>) && __cplusplus >= 201703L
8902 #include <optional>
8903 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8904 #endif
8905 #endif
8906 #endif
8907
8908 // ----------- #included from clara_textflow.hpp -----------
8909
8910 // TextFlowCpp
8911 //
8912 // A single-header library for wrapping and laying out basic text, by Phil Nash
8913 //
8914 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8915 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8916 //
8917 // This project is hosted at https://github.com/philsquared/textflowcpp
8918
8919 #include <cassert>
8920 #include <ostream>
8921 #include <sstream>
8922 #include <vector>
8923
8924 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8925 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8926 #endif
8927
8928 namespace Catch {
8929     namespace clara {
8930         namespace TextFlow {
8931
8932             inline auto isWhitespace(char c) -> bool {
8933                 static std::string chars = " \t\n\r";
8934                 return chars.find(c) != std::string::npos;
8935             }
8936             inline auto isBreakableBefore(char c) -> bool {
8937                 static std::string chars = "[({<|";
8938                 return chars.find(c) != std::string::npos;
8939             }
8940             inline auto isBreakableAfter(char c) -> bool {
8941                 static std::string chars = "])}>.,:;*+-=&/\\";
8942                 return chars.find(c) != std::string::npos;
8943             }
8944
8945             class Columns;
8946
8947             class Column {
8948                 std::vector<std::string> m_strings;
8949                 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8950                 size_t m_indent = 0;
8951                 size_t m_initialIndent = std::string::npos;
8952
8953             public:
8954                 class iterator {
8955                     friend Column;
8956
8957                     Column const& m_column;
8958                     size_t m_stringIndex = 0;
8959                     size_t m_pos = 0;
8960
8961                     size_t m_len = 0;
8962                     size_t m_end = 0;
8963                     bool m_suffix = false;
8964
8965                     iterator(Column const& column, size_t stringIndex) :
8966                         m_column(column), m_stringIndex(stringIndex) {}
8967
8968                     auto line() const -> std::string const& {
8969                         return m_column.m_strings[m_stringIndex];
8970                     }
8971
8972                     auto isBoundary(size_t at) const -> bool {
8973                         assert(at > 0);
8974                         assert(at <= line().size());
8975
8976                         return at == line().size() ||
8977                                (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8978                                isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]);
8979                     }
8980
8981                     void calcLength() {
8982                         assert(m_stringIndex < m_column.m_strings.size());
8983
8984                         m_suffix = false;
8985                         auto width = m_column.m_width - indent();
8986                         m_end = m_pos;
8987                         if (line()[m_pos] == '\n') {
8988                             ++m_end;
8989                         }
8990                         while (m_end < line().size() && line()[m_end] != '\n')
8991                             ++m_end;
8992
8993                         if (m_end < m_pos + width) {
8994                             m_len = m_end - m_pos;
8995                         } else {
8996                             size_t len = width;
8997                             while (len > 0 && !isBoundary(m_pos + len))
8998                                 --len;
8999                             while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
9000                                 --len;
9001
9002                             if (len > 0) {
9003                                 m_len = len;
9004                             } else {
9005                                 m_suffix = true;
9006                                 m_len = width - 1;
9007                             }
9008                         }
9009                     }
9010
9011                     auto indent() const -> size_t {
9012                         auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent
9013                                                                         : std::string::npos;
9014                         return initial == std::string::npos ? m_column.m_indent : initial;
9015                     }
9016
9017                     auto addIndentAndSuffix(std::string const& plain) const -> std::string {
9018                         return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
9019                     }
9020
9021                 public:
9022                     using difference_type = std::ptrdiff_t;
9023                     using value_type = std::string;
9024                     using pointer = value_type*;
9025                     using reference = value_type&;
9026                     using iterator_category = std::forward_iterator_tag;
9027
9028                     explicit iterator(Column const& column) : m_column(column) {
9029                         assert(m_column.m_width > m_column.m_indent);
9030                         assert(m_column.m_initialIndent == std::string::npos ||
9031                                m_column.m_width > m_column.m_initialIndent);
9032                         calcLength();
9033                         if (m_len == 0)
9034                             m_stringIndex++; // Empty string
9035                     }
9036
9037                     auto operator*() const -> std::string {
9038                         assert(m_stringIndex < m_column.m_strings.size());
9039                         assert(m_pos <= m_end);
9040                         return addIndentAndSuffix(line().substr(m_pos, m_len));
9041                     }
9042
9043                     auto operator++() -> iterator& {
9044                         m_pos += m_len;
9045                         if (m_pos < line().size() && line()[m_pos] == '\n')
9046                             m_pos += 1;
9047                         else
9048                             while (m_pos < line().size() && isWhitespace(line()[m_pos]))
9049                                 ++m_pos;
9050
9051                         if (m_pos == line().size()) {
9052                             m_pos = 0;
9053                             ++m_stringIndex;
9054                         }
9055                         if (m_stringIndex < m_column.m_strings.size())
9056                             calcLength();
9057                         return *this;
9058                     }
9059                     auto operator++(int) -> iterator {
9060                         iterator prev(*this);
9061                         operator++();
9062                         return prev;
9063                     }
9064
9065                     auto operator==(iterator const& other) const -> bool {
9066                         return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex &&
9067                                &m_column == &other.m_column;
9068                     }
9069                     auto operator!=(iterator const& other) const -> bool {
9070                         return !operator==(other);
9071                     }
9072                 };
9073                 using const_iterator = iterator;
9074
9075                 explicit Column(std::string const& text) { m_strings.push_back(text); }
9076
9077                 auto width(size_t newWidth) -> Column& {
9078                     assert(newWidth > 0);
9079                     m_width = newWidth;
9080                     return *this;
9081                 }
9082                 auto indent(size_t newIndent) -> Column& {
9083                     m_indent = newIndent;
9084                     return *this;
9085                 }
9086                 auto initialIndent(size_t newIndent) -> Column& {
9087                     m_initialIndent = newIndent;
9088                     return *this;
9089                 }
9090
9091                 auto width() const -> size_t { return m_width; }
9092                 auto begin() const -> iterator { return iterator(*this); }
9093                 auto end() const -> iterator { return {*this, m_strings.size()}; }
9094
9095                 inline friend std::ostream& operator<<(std::ostream& os, Column const& col) {
9096                     bool first = true;
9097                     for (auto line : col) {
9098                         if (first)
9099                             first = false;
9100                         else
9101                             os << "\n";
9102                         os << line;
9103                     }
9104                     return os;
9105                 }
9106
9107                 auto operator+(Column const& other) -> Columns;
9108
9109                 auto toString() const -> std::string {
9110                     std::ostringstream oss;
9111                     oss << *this;
9112                     return oss.str();
9113                 }
9114             };
9115
9116             class Spacer : public Column {
9117
9118             public:
9119                 explicit Spacer(size_t spaceWidth) : Column("") { width(spaceWidth); }
9120             };
9121
9122             class Columns {
9123                 std::vector<Column> m_columns;
9124
9125             public:
9126                 class iterator {
9127                     friend Columns;
9128                     struct EndTag {};
9129
9130                     std::vector<Column> const& m_columns;
9131                     std::vector<Column::iterator> m_iterators;
9132                     size_t m_activeIterators;
9133
9134                     iterator(Columns const& columns, EndTag) :
9135                         m_columns(columns.m_columns), m_activeIterators(0) {
9136                         m_iterators.reserve(m_columns.size());
9137
9138                         for (auto const& col : m_columns)
9139                             m_iterators.push_back(col.end());
9140                     }
9141
9142                 public:
9143                     using difference_type = std::ptrdiff_t;
9144                     using value_type = std::string;
9145                     using pointer = value_type*;
9146                     using reference = value_type&;
9147                     using iterator_category = std::forward_iterator_tag;
9148
9149                     explicit iterator(Columns const& columns) :
9150                         m_columns(columns.m_columns), m_activeIterators(m_columns.size()) {
9151                         m_iterators.reserve(m_columns.size());
9152
9153                         for (auto const& col : m_columns)
9154                             m_iterators.push_back(col.begin());
9155                     }
9156
9157                     auto operator==(iterator const& other) const -> bool {
9158                         return m_iterators == other.m_iterators;
9159                     }
9160                     auto operator!=(iterator const& other) const -> bool {
9161                         return m_iterators != other.m_iterators;
9162                     }
9163                     auto operator*() const -> std::string {
9164                         std::string row, padding;
9165
9166                         for (size_t i = 0; i < m_columns.size(); ++i) {
9167                             auto width = m_columns[i].width();
9168                             if (m_iterators[i] != m_columns[i].end()) {
9169                                 std::string col = *m_iterators[i];
9170                                 row += padding + col;
9171                                 if (col.size() < width)
9172                                     padding = std::string(width - col.size(), ' ');
9173                                 else
9174                                     padding = "";
9175                             } else {
9176                                 padding += std::string(width, ' ');
9177                             }
9178                         }
9179                         return row;
9180                     }
9181                     auto operator++() -> iterator& {
9182                         for (size_t i = 0; i < m_columns.size(); ++i) {
9183                             if (m_iterators[i] != m_columns[i].end())
9184                                 ++m_iterators[i];
9185                         }
9186                         return *this;
9187                     }
9188                     auto operator++(int) -> iterator {
9189                         iterator prev(*this);
9190                         operator++();
9191                         return prev;
9192                     }
9193                 };
9194                 using const_iterator = iterator;
9195
9196                 auto begin() const -> iterator { return iterator(*this); }
9197                 auto end() const -> iterator { return {*this, iterator::EndTag()}; }
9198
9199                 auto operator+=(Column const& col) -> Columns& {
9200                     m_columns.push_back(col);
9201                     return *this;
9202                 }
9203                 auto operator+(Column const& col) -> Columns {
9204                     Columns combined = *this;
9205                     combined += col;
9206                     return combined;
9207                 }
9208
9209                 inline friend std::ostream& operator<<(std::ostream& os, Columns const& cols) {
9210
9211                     bool first = true;
9212                     for (auto line : cols) {
9213                         if (first)
9214                             first = false;
9215                         else
9216                             os << "\n";
9217                         os << line;
9218                     }
9219                     return os;
9220                 }
9221
9222                 auto toString() const -> std::string {
9223                     std::ostringstream oss;
9224                     oss << *this;
9225                     return oss.str();
9226                 }
9227             };
9228
9229             inline auto Column::operator+(Column const& other) -> Columns {
9230                 Columns cols;
9231                 cols += *this;
9232                 cols += other;
9233                 return cols;
9234             }
9235         } // namespace TextFlow
9236
9237     } // namespace clara
9238 } // namespace Catch
9239
9240 // ----------- end of #include from clara_textflow.hpp -----------
9241 // ........... back in clara.hpp
9242
9243 #include <cctype>
9244 #include <string>
9245 #include <memory>
9246 #include <set>
9247 #include <algorithm>
9248
9249 #if !defined(CATCH_PLATFORM_WINDOWS) &&                                                            \
9250     (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER))
9251 #define CATCH_PLATFORM_WINDOWS
9252 #endif
9253
9254 namespace Catch {
9255     namespace clara {
9256         namespace detail {
9257
9258             // Traits for extracting arg and return type of lambdas (for single
9259             // argument lambdas)
9260             template <typename L>
9261             struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())> {};
9262
9263             template <typename ClassT, typename ReturnT, typename... Args>
9264             struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const> {
9265                 static const bool isValid = false;
9266             };
9267
9268             template <typename ClassT, typename ReturnT, typename ArgT>
9269             struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const> {
9270                 static const bool isValid = true;
9271                 using ArgType =
9272                     typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
9273                 using ReturnType = ReturnT;
9274             };
9275
9276             class TokenStream;
9277
9278             // Transport for raw args (copied from main args, or supplied via
9279             // init list for testing)
9280             class Args {
9281                 friend TokenStream;
9282                 std::string m_exeName;
9283                 std::vector<std::string> m_args;
9284
9285             public:
9286                 Args(int argc, char const* const* argv) :
9287                     m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
9288
9289                 Args(std::initializer_list<std::string> args) :
9290                     m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {}
9291
9292                 auto exeName() const -> std::string { return m_exeName; }
9293             };
9294
9295             // Wraps a token coming from a token stream. These may not directly
9296             // correspond to strings as a single string may encode an option +
9297             // its argument if the : or = form is used
9298             enum class TokenType { Option, Argument };
9299             struct Token {
9300                 TokenType type;
9301                 std::string token;
9302             };
9303
9304             inline auto isOptPrefix(char c) -> bool {
9305                 return c == '-'
9306 #ifdef CATCH_PLATFORM_WINDOWS
9307                        || c == '/'
9308 #endif
9309                     ;
9310             }
9311
9312             // Abstracts iterators into args as a stream of tokens, with option
9313             // arguments uniformly handled
9314             class TokenStream {
9315                 using Iterator = std::vector<std::string>::const_iterator;
9316                 Iterator it;
9317                 Iterator itEnd;
9318                 std::vector<Token> m_tokenBuffer;
9319
9320                 void loadBuffer() {
9321                     m_tokenBuffer.resize(0);
9322
9323                     // Skip any empty strings
9324                     while (it != itEnd && it->empty())
9325                         ++it;
9326
9327                     if (it != itEnd) {
9328                         auto const& next = *it;
9329                         if (isOptPrefix(next[0])) {
9330                             auto delimiterPos = next.find_first_of(" :=");
9331                             if (delimiterPos != std::string::npos) {
9332                                 m_tokenBuffer.push_back(
9333                                     {TokenType::Option, next.substr(0, delimiterPos)});
9334                                 m_tokenBuffer.push_back(
9335                                     {TokenType::Argument, next.substr(delimiterPos + 1)});
9336                             } else {
9337                                 if (next[1] != '-' && next.size() > 2) {
9338                                     std::string opt = "- ";
9339                                     for (size_t i = 1; i < next.size(); ++i) {
9340                                         opt[1] = next[i];
9341                                         m_tokenBuffer.push_back({TokenType::Option, opt});
9342                                     }
9343                                 } else {
9344                                     m_tokenBuffer.push_back({TokenType::Option, next});
9345                                 }
9346                             }
9347                         } else {
9348                             m_tokenBuffer.push_back({TokenType::Argument, next});
9349                         }
9350                     }
9351                 }
9352
9353             public:
9354                 explicit TokenStream(Args const& args) :
9355                     TokenStream(args.m_args.begin(), args.m_args.end()) {}
9356
9357                 TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); }
9358
9359                 explicit operator bool() const { return !m_tokenBuffer.empty() || it != itEnd; }
9360
9361                 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
9362
9363                 auto operator*() const -> Token {
9364                     assert(!m_tokenBuffer.empty());
9365                     return m_tokenBuffer.front();
9366                 }
9367
9368                 auto operator->() const -> Token const* {
9369                     assert(!m_tokenBuffer.empty());
9370                     return &m_tokenBuffer.front();
9371                 }
9372
9373                 auto operator++() -> TokenStream& {
9374                     if (m_tokenBuffer.size() >= 2) {
9375                         m_tokenBuffer.erase(m_tokenBuffer.begin());
9376                     } else {
9377                         if (it != itEnd)
9378                             ++it;
9379                         loadBuffer();
9380                     }
9381                     return *this;
9382                 }
9383             };
9384
9385             class ResultBase {
9386             public:
9387                 enum Type { Ok, LogicError, RuntimeError };
9388
9389             protected:
9390                 ResultBase(Type type) : m_type(type) {}
9391                 virtual ~ResultBase() = default;
9392
9393                 virtual void enforceOk() const = 0;
9394
9395                 Type m_type;
9396             };
9397
9398             template <typename T> class ResultValueBase : public ResultBase {
9399             public:
9400                 auto value() const -> T const& {
9401                     enforceOk();
9402                     return m_value;
9403                 }
9404
9405             protected:
9406                 ResultValueBase(Type type) : ResultBase(type) {}
9407
9408                 ResultValueBase(ResultValueBase const& other) : ResultBase(other) {
9409                     if (m_type == ResultBase::Ok)
9410                         new (&m_value) T(other.m_value);
9411                 }
9412
9413                 ResultValueBase(Type, T const& value) : ResultBase(Ok) { new (&m_value) T(value); }
9414
9415                 auto operator=(ResultValueBase const& other) -> ResultValueBase& {
9416                     if (m_type == ResultBase::Ok)
9417                         m_value.~T();
9418                     ResultBase::operator=(other);
9419                     if (m_type == ResultBase::Ok)
9420                         new (&m_value) T(other.m_value);
9421                     return *this;
9422                 }
9423
9424                 ~ResultValueBase() override {
9425                     if (m_type == Ok)
9426                         m_value.~T();
9427                 }
9428
9429                 union {
9430                     T m_value;
9431                 };
9432             };
9433
9434             template <> class ResultValueBase<void> : public ResultBase {
9435             protected:
9436                 using ResultBase::ResultBase;
9437             };
9438
9439             template <typename T = void> class BasicResult : public ResultValueBase<T> {
9440             public:
9441                 template <typename U>
9442                 explicit BasicResult(BasicResult<U> const& other) :
9443                     ResultValueBase<T>(other.type()), m_errorMessage(other.errorMessage()) {
9444                     assert(type() != ResultBase::Ok);
9445                 }
9446
9447                 template <typename U> static auto ok(U const& value) -> BasicResult {
9448                     return {ResultBase::Ok, value};
9449                 }
9450                 static auto ok() -> BasicResult { return {ResultBase::Ok}; }
9451                 static auto logicError(std::string const& message) -> BasicResult {
9452                     return {ResultBase::LogicError, message};
9453                 }
9454                 static auto runtimeError(std::string const& message) -> BasicResult {
9455                     return {ResultBase::RuntimeError, message};
9456                 }
9457
9458                 explicit operator bool() const { return m_type == ResultBase::Ok; }
9459                 auto type() const -> ResultBase::Type { return m_type; }
9460                 auto errorMessage() const -> std::string { return m_errorMessage; }
9461
9462             protected:
9463                 void enforceOk() const override {
9464
9465                     // Errors shouldn't reach this point, but if they do
9466                     // the actual error message will be in m_errorMessage
9467                     assert(m_type != ResultBase::LogicError);
9468                     assert(m_type != ResultBase::RuntimeError);
9469                     if (m_type != ResultBase::Ok)
9470                         std::abort();
9471                 }
9472
9473                 std::string m_errorMessage; // Only populated if resultType is an error
9474
9475                 BasicResult(ResultBase::Type type, std::string const& message) :
9476                     ResultValueBase<T>(type), m_errorMessage(message) {
9477                     assert(m_type != ResultBase::Ok);
9478                 }
9479
9480                 using ResultValueBase<T>::ResultValueBase;
9481                 using ResultBase::m_type;
9482             };
9483
9484             enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame };
9485
9486             class ParseState {
9487             public:
9488                 ParseState(ParseResultType type, TokenStream const& remainingTokens) :
9489                     m_type(type), m_remainingTokens(remainingTokens) {}
9490
9491                 auto type() const -> ParseResultType { return m_type; }
9492                 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9493
9494             private:
9495                 ParseResultType m_type;
9496                 TokenStream m_remainingTokens;
9497             };
9498
9499             using Result = BasicResult<void>;
9500             using ParserResult = BasicResult<ParseResultType>;
9501             using InternalParseResult = BasicResult<ParseState>;
9502
9503             struct HelpColumns {
9504                 std::string left;
9505                 std::string right;
9506             };
9507
9508             template <typename T>
9509             inline auto convertInto(std::string const& source, T& target) -> ParserResult {
9510                 std::stringstream ss;
9511                 ss << source;
9512                 ss >> target;
9513                 if (ss.fail())
9514                     return ParserResult::runtimeError("Unable to convert '" + source +
9515                                                       "' to destination type");
9516                 else
9517                     return ParserResult::ok(ParseResultType::Matched);
9518             }
9519             inline auto convertInto(std::string const& source, std::string& target)
9520                 -> ParserResult {
9521                 target = source;
9522                 return ParserResult::ok(ParseResultType::Matched);
9523             }
9524             inline auto convertInto(std::string const& source, bool& target) -> ParserResult {
9525                 std::string srcLC = source;
9526                 std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(), [](unsigned char c) {
9527                     return static_cast<char>(std::tolower(c));
9528                 });
9529                 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" ||
9530                     srcLC == "on")
9531                     target = true;
9532                 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" ||
9533                          srcLC == "off")
9534                     target = false;
9535                 else
9536                     return ParserResult::runtimeError(
9537                         "Expected a boolean value but did not recognise: '" + source + "'");
9538                 return ParserResult::ok(ParseResultType::Matched);
9539             }
9540 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9541             template <typename T>
9542             inline auto convertInto(std::string const& source,
9543                                     CLARA_CONFIG_OPTIONAL_TYPE<T>& target) -> ParserResult {
9544                 T temp;
9545                 auto result = convertInto(source, temp);
9546                 if (result)
9547                     target = std::move(temp);
9548                 return result;
9549             }
9550 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9551
9552             struct NonCopyable {
9553                 NonCopyable() = default;
9554                 NonCopyable(NonCopyable const&) = delete;
9555                 NonCopyable(NonCopyable&&) = delete;
9556                 NonCopyable& operator=(NonCopyable const&) = delete;
9557                 NonCopyable& operator=(NonCopyable&&) = delete;
9558             };
9559
9560             struct BoundRef : NonCopyable {
9561                 virtual ~BoundRef() = default;
9562                 virtual auto isContainer() const -> bool { return false; }
9563                 virtual auto isFlag() const -> bool { return false; }
9564             };
9565             struct BoundValueRefBase : BoundRef {
9566                 virtual auto setValue(std::string const& arg) -> ParserResult = 0;
9567             };
9568             struct BoundFlagRefBase : BoundRef {
9569                 virtual auto setFlag(bool flag) -> ParserResult = 0;
9570                 virtual auto isFlag() const -> bool { return true; }
9571             };
9572
9573             template <typename T> struct BoundValueRef : BoundValueRefBase {
9574                 T& m_ref;
9575
9576                 explicit BoundValueRef(T& ref) : m_ref(ref) {}
9577
9578                 auto setValue(std::string const& arg) -> ParserResult override {
9579                     return convertInto(arg, m_ref);
9580                 }
9581             };
9582
9583             template <typename T> struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9584                 std::vector<T>& m_ref;
9585
9586                 explicit BoundValueRef(std::vector<T>& ref) : m_ref(ref) {}
9587
9588                 auto isContainer() const -> bool override { return true; }
9589
9590                 auto setValue(std::string const& arg) -> ParserResult override {
9591                     T temp;
9592                     auto result = convertInto(arg, temp);
9593                     if (result)
9594                         m_ref.push_back(temp);
9595                     return result;
9596                 }
9597             };
9598
9599             struct BoundFlagRef : BoundFlagRefBase {
9600                 bool& m_ref;
9601
9602                 explicit BoundFlagRef(bool& ref) : m_ref(ref) {}
9603
9604                 auto setFlag(bool flag) -> ParserResult override {
9605                     m_ref = flag;
9606                     return ParserResult::ok(ParseResultType::Matched);
9607                 }
9608             };
9609
9610             template <typename ReturnType> struct LambdaInvoker {
9611                 static_assert(std::is_same<ReturnType, ParserResult>::value,
9612                               "Lambda must return void or clara::ParserResult");
9613
9614                 template <typename L, typename ArgType>
9615                 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9616                     return lambda(arg);
9617                 }
9618             };
9619
9620             template <> struct LambdaInvoker<void> {
9621                 template <typename L, typename ArgType>
9622                 static auto invoke(L const& lambda, ArgType const& arg) -> ParserResult {
9623                     lambda(arg);
9624                     return ParserResult::ok(ParseResultType::Matched);
9625                 }
9626             };
9627
9628             template <typename ArgType, typename L>
9629             inline auto invokeLambda(L const& lambda, std::string const& arg) -> ParserResult {
9630                 ArgType temp{};
9631                 auto result = convertInto(arg, temp);
9632                 return !result ? result
9633                                : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(
9634                                      lambda, temp);
9635             }
9636
9637             template <typename L> struct BoundLambda : BoundValueRefBase {
9638                 L m_lambda;
9639
9640                 static_assert(UnaryLambdaTraits<L>::isValid,
9641                               "Supplied lambda must take exactly one argument");
9642                 explicit BoundLambda(L const& lambda) : m_lambda(lambda) {}
9643
9644                 auto setValue(std::string const& arg) -> ParserResult override {
9645                     return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
9646                 }
9647             };
9648
9649             template <typename L> struct BoundFlagLambda : BoundFlagRefBase {
9650                 L m_lambda;
9651
9652                 static_assert(UnaryLambdaTraits<L>::isValid,
9653                               "Supplied lambda must take exactly one argument");
9654                 static_assert(std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value,
9655                               "flags must be boolean");
9656
9657                 explicit BoundFlagLambda(L const& lambda) : m_lambda(lambda) {}
9658
9659                 auto setFlag(bool flag) -> ParserResult override {
9660                     return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(
9661                         m_lambda, flag);
9662                 }
9663             };
9664
9665             enum class Optionality { Optional, Required };
9666
9667             struct Parser;
9668
9669             class ParserBase {
9670             public:
9671                 virtual ~ParserBase() = default;
9672                 virtual auto validate() const -> Result { return Result::ok(); }
9673                 virtual auto parse(std::string const& exeName, TokenStream const& tokens) const
9674                     -> InternalParseResult = 0;
9675                 virtual auto cardinality() const -> size_t { return 1; }
9676
9677                 auto parse(Args const& args) const -> InternalParseResult {
9678                     return parse(args.exeName(), TokenStream(args));
9679                 }
9680             };
9681
9682             template <typename DerivedT> class ComposableParserImpl : public ParserBase {
9683             public:
9684                 template <typename T> auto operator|(T const& other) const -> Parser;
9685
9686                 template <typename T> auto operator+(T const& other) const -> Parser;
9687             };
9688
9689             // Common code and state for Args and Opts
9690             template <typename DerivedT>
9691             class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9692             protected:
9693                 Optionality m_optionality = Optionality::Optional;
9694                 std::shared_ptr<BoundRef> m_ref;
9695                 std::string m_hint;
9696                 std::string m_description;
9697
9698                 explicit ParserRefImpl(std::shared_ptr<BoundRef> const& ref) : m_ref(ref) {}
9699
9700             public:
9701                 template <typename T>
9702                 ParserRefImpl(T& ref, std::string const& hint) :
9703                     m_ref(std::make_shared<BoundValueRef<T>>(ref)), m_hint(hint) {}
9704
9705                 template <typename LambdaT>
9706                 ParserRefImpl(LambdaT const& ref, std::string const& hint) :
9707                     m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), m_hint(hint) {}
9708
9709                 auto operator()(std::string const& description) -> DerivedT& {
9710                     m_description = description;
9711                     return static_cast<DerivedT&>(*this);
9712                 }
9713
9714                 auto optional() -> DerivedT& {
9715                     m_optionality = Optionality::Optional;
9716                     return static_cast<DerivedT&>(*this);
9717                 };
9718
9719                 auto required() -> DerivedT& {
9720                     m_optionality = Optionality::Required;
9721                     return static_cast<DerivedT&>(*this);
9722                 };
9723
9724                 auto isOptional() const -> bool { return m_optionality == Optionality::Optional; }
9725
9726                 auto cardinality() const -> size_t override {
9727                     if (m_ref->isContainer())
9728                         return 0;
9729                     else
9730                         return 1;
9731                 }
9732
9733                 auto hint() const -> std::string { return m_hint; }
9734             };
9735
9736             class ExeName : public ComposableParserImpl<ExeName> {
9737                 std::shared_ptr<std::string> m_name;
9738                 std::shared_ptr<BoundValueRefBase> m_ref;
9739
9740                 template <typename LambdaT>
9741                 static auto makeRef(LambdaT const& lambda) -> std::shared_ptr<BoundValueRefBase> {
9742                     return std::make_shared<BoundLambda<LambdaT>>(lambda);
9743                 }
9744
9745             public:
9746                 ExeName() : m_name(std::make_shared<std::string>("<executable>")) {}
9747
9748                 explicit ExeName(std::string& ref) : ExeName() {
9749                     m_ref = std::make_shared<BoundValueRef<std::string>>(ref);
9750                 }
9751
9752                 template <typename LambdaT> explicit ExeName(LambdaT const& lambda) : ExeName() {
9753                     m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda);
9754                 }
9755
9756                 // The exe name is not parsed out of the normal tokens, but is
9757                 // handled specially
9758                 auto parse(std::string const&, TokenStream const& tokens) const
9759                     -> InternalParseResult override {
9760                     return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9761                 }
9762
9763                 auto name() const -> std::string { return *m_name; }
9764                 auto set(std::string const& newName) -> ParserResult {
9765
9766                     auto lastSlash = newName.find_last_of("\\/");
9767                     auto filename =
9768                         (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1);
9769
9770                     *m_name = filename;
9771                     if (m_ref)
9772                         return m_ref->setValue(filename);
9773                     else
9774                         return ParserResult::ok(ParseResultType::Matched);
9775                 }
9776             };
9777
9778             class Arg : public ParserRefImpl<Arg> {
9779             public:
9780                 using ParserRefImpl::ParserRefImpl;
9781
9782                 auto parse(std::string const&, TokenStream const& tokens) const
9783                     -> InternalParseResult override {
9784                     auto validationResult = validate();
9785                     if (!validationResult)
9786                         return InternalParseResult(validationResult);
9787
9788                     auto remainingTokens = tokens;
9789                     auto const& token = *remainingTokens;
9790                     if (token.type != TokenType::Argument)
9791                         return InternalParseResult::ok(
9792                             ParseState(ParseResultType::NoMatch, remainingTokens));
9793
9794                     assert(!m_ref->isFlag());
9795                     auto valueRef = static_cast<detail::BoundValueRefBase*>(m_ref.get());
9796
9797                     auto result = valueRef->setValue(remainingTokens->token);
9798                     if (!result)
9799                         return InternalParseResult(result);
9800                     else
9801                         return InternalParseResult::ok(
9802                             ParseState(ParseResultType::Matched, ++remainingTokens));
9803                 }
9804             };
9805
9806             inline auto normaliseOpt(std::string const& optName) -> std::string {
9807 #ifdef CATCH_PLATFORM_WINDOWS
9808                 if (optName[0] == '/')
9809                     return "-" + optName.substr(1);
9810                 else
9811 #endif
9812                     return optName;
9813             }
9814
9815             class Opt : public ParserRefImpl<Opt> {
9816             protected:
9817                 std::vector<std::string> m_optNames;
9818
9819             public:
9820                 template <typename LambdaT>
9821                 explicit Opt(LambdaT const& ref) :
9822                     ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {}
9823
9824                 explicit Opt(bool& ref) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
9825
9826                 template <typename LambdaT>
9827                 Opt(LambdaT const& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9828
9829                 template <typename T>
9830                 Opt(T& ref, std::string const& hint) : ParserRefImpl(ref, hint) {}
9831
9832                 auto operator[](std::string const& optName) -> Opt& {
9833                     m_optNames.push_back(optName);
9834                     return *this;
9835                 }
9836
9837                 auto getHelpColumns() const -> std::vector<HelpColumns> {
9838                     std::ostringstream oss;
9839                     bool first = true;
9840                     for (auto const& opt : m_optNames) {
9841                         if (first)
9842                             first = false;
9843                         else
9844                             oss << ", ";
9845                         oss << opt;
9846                     }
9847                     if (!m_hint.empty())
9848                         oss << " <" << m_hint << ">";
9849                     return {{oss.str(), m_description}};
9850                 }
9851
9852                 auto isMatch(std::string const& optToken) const -> bool {
9853                     auto normalisedToken = normaliseOpt(optToken);
9854                     for (auto const& name : m_optNames) {
9855                         if (normaliseOpt(name) == normalisedToken)
9856                             return true;
9857                     }
9858                     return false;
9859                 }
9860
9861                 using ParserBase::parse;
9862
9863                 auto parse(std::string const&, TokenStream const& tokens) const
9864                     -> InternalParseResult override {
9865                     auto validationResult = validate();
9866                     if (!validationResult)
9867                         return InternalParseResult(validationResult);
9868
9869                     auto remainingTokens = tokens;
9870                     if (remainingTokens && remainingTokens->type == TokenType::Option) {
9871                         auto const& token = *remainingTokens;
9872                         if (isMatch(token.token)) {
9873                             if (m_ref->isFlag()) {
9874                                 auto flagRef = static_cast<detail::BoundFlagRefBase*>(m_ref.get());
9875                                 auto result = flagRef->setFlag(true);
9876                                 if (!result)
9877                                     return InternalParseResult(result);
9878                                 if (result.value() == ParseResultType::ShortCircuitAll)
9879                                     return InternalParseResult::ok(
9880                                         ParseState(result.value(), remainingTokens));
9881                             } else {
9882                                 auto valueRef =
9883                                     static_cast<detail::BoundValueRefBase*>(m_ref.get());
9884                                 ++remainingTokens;
9885                                 if (!remainingTokens)
9886                                     return InternalParseResult::runtimeError(
9887                                         "Expected argument following " + token.token);
9888                                 auto const& argToken = *remainingTokens;
9889                                 if (argToken.type != TokenType::Argument)
9890                                     return InternalParseResult::runtimeError(
9891                                         "Expected argument following " + token.token);
9892                                 auto result = valueRef->setValue(argToken.token);
9893                                 if (!result)
9894                                     return InternalParseResult(result);
9895                                 if (result.value() == ParseResultType::ShortCircuitAll)
9896                                     return InternalParseResult::ok(
9897                                         ParseState(result.value(), remainingTokens));
9898                             }
9899                             return InternalParseResult::ok(
9900                                 ParseState(ParseResultType::Matched, ++remainingTokens));
9901                         }
9902                     }
9903                     return InternalParseResult::ok(
9904                         ParseState(ParseResultType::NoMatch, remainingTokens));
9905                 }
9906
9907                 auto validate() const -> Result override {
9908                     if (m_optNames.empty())
9909                         return Result::logicError("No options supplied to Opt");
9910                     for (auto const& name : m_optNames) {
9911                         if (name.empty())
9912                             return Result::logicError("Option name cannot be empty");
9913 #ifdef CATCH_PLATFORM_WINDOWS
9914                         if (name[0] != '-' && name[0] != '/')
9915                             return Result::logicError("Option name must begin with '-' or '/'");
9916 #else
9917                         if (name[0] != '-')
9918                             return Result::logicError("Option name must begin with '-'");
9919 #endif
9920                     }
9921                     return ParserRefImpl::validate();
9922                 }
9923             };
9924
9925             struct Help : Opt {
9926                 Help(bool& showHelpFlag) :
9927                     Opt([&](bool flag) {
9928                         showHelpFlag = flag;
9929                         return ParserResult::ok(ParseResultType::ShortCircuitAll);
9930                     }) {
9931                     static_cast<Opt&> (*this)("display usage information")["-?"]["-h"]["--help"]
9932                         .optional();
9933                 }
9934             };
9935
9936             struct Parser : ParserBase {
9937
9938                 mutable ExeName m_exeName;
9939                 std::vector<Opt> m_options;
9940                 std::vector<Arg> m_args;
9941
9942                 auto operator|=(ExeName const& exeName) -> Parser& {
9943                     m_exeName = exeName;
9944                     return *this;
9945                 }
9946
9947                 auto operator|=(Arg const& arg) -> Parser& {
9948                     m_args.push_back(arg);
9949                     return *this;
9950                 }
9951
9952                 auto operator|=(Opt const& opt) -> Parser& {
9953                     m_options.push_back(opt);
9954                     return *this;
9955                 }
9956
9957                 auto operator|=(Parser const& other) -> Parser& {
9958                     m_options.insert(
9959                         m_options.end(), other.m_options.begin(), other.m_options.end());
9960                     m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9961                     return *this;
9962                 }
9963
9964                 template <typename T> auto operator|(T const& other) const -> Parser {
9965                     return Parser(*this) |= other;
9966                 }
9967
9968                 // Forward deprecated interface with '+' instead of '|'
9969                 template <typename T> auto operator+=(T const& other) -> Parser& {
9970                     return operator|=(other);
9971                 }
9972                 template <typename T> auto operator+(T const& other) const -> Parser {
9973                     return operator|(other);
9974                 }
9975
9976                 auto getHelpColumns() const -> std::vector<HelpColumns> {
9977                     std::vector<HelpColumns> cols;
9978                     for (auto const& o : m_options) {
9979                         auto childCols = o.getHelpColumns();
9980                         cols.insert(cols.end(), childCols.begin(), childCols.end());
9981                     }
9982                     return cols;
9983                 }
9984
9985                 void writeToStream(std::ostream& os) const {
9986                     if (!m_exeName.name().empty()) {
9987                         os << "usage:\n"
9988                            << "  " << m_exeName.name() << " ";
9989                         bool required = true, first = true;
9990                         for (auto const& arg : m_args) {
9991                             if (first)
9992                                 first = false;
9993                             else
9994                                 os << " ";
9995                             if (arg.isOptional() && required) {
9996                                 os << "[";
9997                                 required = false;
9998                             }
9999                             os << "<" << arg.hint() << ">";
10000                             if (arg.cardinality() == 0)
10001                                 os << " ... ";
10002                         }
10003                         if (!required)
10004                             os << "]";
10005                         if (!m_options.empty())
10006                             os << " options";
10007                         os << "\n\nwhere options are:" << std::endl;
10008                     }
10009
10010                     auto rows = getHelpColumns();
10011                     size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
10012                     size_t optWidth = 0;
10013                     for (auto const& cols : rows)
10014                         optWidth = (std::max)(optWidth, cols.left.size() + 2);
10015
10016                     optWidth = (std::min)(optWidth, consoleWidth / 2);
10017
10018                     for (auto const& cols : rows) {
10019                         auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) +
10020                                    TextFlow::Spacer(4) +
10021                                    TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
10022                         os << row << std::endl;
10023                     }
10024                 }
10025
10026                 friend auto operator<<(std::ostream& os, Parser const& parser) -> std::ostream& {
10027                     parser.writeToStream(os);
10028                     return os;
10029                 }
10030
10031                 auto validate() const -> Result override {
10032                     for (auto const& opt : m_options) {
10033                         auto result = opt.validate();
10034                         if (!result)
10035                             return result;
10036                     }
10037                     for (auto const& arg : m_args) {
10038                         auto result = arg.validate();
10039                         if (!result)
10040                             return result;
10041                     }
10042                     return Result::ok();
10043                 }
10044
10045                 using ParserBase::parse;
10046
10047                 auto parse(std::string const& exeName, TokenStream const& tokens) const
10048                     -> InternalParseResult override {
10049
10050                     struct ParserInfo {
10051                         ParserBase const* parser = nullptr;
10052                         size_t count = 0;
10053                     };
10054                     const size_t totalParsers = m_options.size() + m_args.size();
10055                     assert(totalParsers < 512);
10056                     // ParserInfo parseInfos[totalParsers]; // <-- this is what
10057                     // we really want to do
10058                     ParserInfo parseInfos[512];
10059
10060                     {
10061                         size_t i = 0;
10062                         for (auto const& opt : m_options)
10063                             parseInfos[i++].parser = &opt;
10064                         for (auto const& arg : m_args)
10065                             parseInfos[i++].parser = &arg;
10066                     }
10067
10068                     m_exeName.set(exeName);
10069
10070                     auto result =
10071                         InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
10072                     while (result.value().remainingTokens()) {
10073                         bool tokenParsed = false;
10074
10075                         for (size_t i = 0; i < totalParsers; ++i) {
10076                             auto& parseInfo = parseInfos[i];
10077                             if (parseInfo.parser->cardinality() == 0 ||
10078                                 parseInfo.count < parseInfo.parser->cardinality()) {
10079                                 result = parseInfo.parser->parse(exeName,
10080                                                                  result.value().remainingTokens());
10081                                 if (!result)
10082                                     return result;
10083                                 if (result.value().type() != ParseResultType::NoMatch) {
10084                                     tokenParsed = true;
10085                                     ++parseInfo.count;
10086                                     break;
10087                                 }
10088                             }
10089                         }
10090
10091                         if (result.value().type() == ParseResultType::ShortCircuitAll)
10092                             return result;
10093                         if (!tokenParsed)
10094                             return InternalParseResult::runtimeError(
10095                                 "Unrecognised token: " + result.value().remainingTokens()->token);
10096                     }
10097                     // !TBD Check missing required options
10098                     return result;
10099                 }
10100             };
10101
10102             template <typename DerivedT>
10103             template <typename T>
10104             auto ComposableParserImpl<DerivedT>::operator|(T const& other) const -> Parser {
10105                 return Parser() | static_cast<DerivedT const&>(*this) | other;
10106             }
10107         } // namespace detail
10108
10109         // A Combined parser
10110         using detail::Parser;
10111
10112         // A parser for options
10113         using detail::Opt;
10114
10115         // A parser for arguments
10116         using detail::Arg;
10117
10118         // Wrapper for argc, argv from main()
10119         using detail::Args;
10120
10121         // Specifies the name of the executable
10122         using detail::ExeName;
10123
10124         // Convenience wrapper for option parser that specifies the help option
10125         using detail::Help;
10126
10127         // enum of result types from a parse
10128         using detail::ParseResultType;
10129
10130         // Result type for parser operation
10131         using detail::ParserResult;
10132
10133     } // namespace clara
10134 } // namespace Catch
10135
10136 // end clara.hpp
10137 #ifdef __clang__
10138 #pragma clang diagnostic pop
10139 #endif
10140
10141 // Restore Clara's value for console width, if present
10142 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10143 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10144 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
10145 #endif
10146
10147 // end catch_clara.h
10148 namespace Catch {
10149
10150     clara::Parser makeCommandLineParser(ConfigData& config);
10151
10152 } // end namespace Catch
10153
10154 // end catch_commandline.h
10155 #include <fstream>
10156 #include <ctime>
10157
10158 namespace Catch {
10159
10160     clara::Parser makeCommandLineParser(ConfigData& config) {
10161
10162         using namespace clara;
10163
10164         auto const setWarning = [&](std::string const& warning) {
10165             auto warningSet = [&]() {
10166                 if (warning == "NoAssertions")
10167                     return WarnAbout::NoAssertions;
10168
10169                 if (warning == "NoTests")
10170                     return WarnAbout::NoTests;
10171
10172                 return WarnAbout::Nothing;
10173             }();
10174
10175             if (warningSet == WarnAbout::Nothing)
10176                 return ParserResult::runtimeError("Unrecognised warning: '" + warning + "'");
10177             config.warnings = static_cast<WarnAbout::What>(config.warnings | warningSet);
10178             return ParserResult::ok(ParseResultType::Matched);
10179         };
10180         auto const loadTestNamesFromFile = [&](std::string const& filename) {
10181             std::ifstream f(filename.c_str());
10182             if (!f.is_open())
10183                 return ParserResult::runtimeError("Unable to load input file: '" + filename + "'");
10184
10185             std::string line;
10186             while (std::getline(f, line)) {
10187                 line = trim(line);
10188                 if (!line.empty() && !startsWith(line, '#')) {
10189                     if (!startsWith(line, '"'))
10190                         line = '"' + line + '"';
10191                     config.testsOrTags.push_back(line);
10192                     config.testsOrTags.emplace_back(",");
10193                 }
10194             }
10195             // Remove comma in the end
10196             if (!config.testsOrTags.empty())
10197                 config.testsOrTags.erase(config.testsOrTags.end() - 1);
10198
10199             return ParserResult::ok(ParseResultType::Matched);
10200         };
10201         auto const setTestOrder = [&](std::string const& order) {
10202             if (startsWith("declared", order))
10203                 config.runOrder = RunTests::InDeclarationOrder;
10204             else if (startsWith("lexical", order))
10205                 config.runOrder = RunTests::InLexicographicalOrder;
10206             else if (startsWith("random", order))
10207                 config.runOrder = RunTests::InRandomOrder;
10208             else
10209                 return clara::ParserResult::runtimeError("Unrecognised ordering: '" + order + "'");
10210             return ParserResult::ok(ParseResultType::Matched);
10211         };
10212         auto const setRngSeed = [&](std::string const& seed) {
10213             if (seed != "time")
10214                 return clara::detail::convertInto(seed, config.rngSeed);
10215             config.rngSeed = static_cast<unsigned int>(std::time(nullptr));
10216             return ParserResult::ok(ParseResultType::Matched);
10217         };
10218         auto const setColourUsage = [&](std::string const& useColour) {
10219             auto mode = toLower(useColour);
10220
10221             if (mode == "yes")
10222                 config.useColour = UseColour::Yes;
10223             else if (mode == "no")
10224                 config.useColour = UseColour::No;
10225             else if (mode == "auto")
10226                 config.useColour = UseColour::Auto;
10227             else
10228                 return ParserResult::runtimeError("colour mode must be one of: auto, yes or no. '" +
10229                                                   useColour + "' not recognised");
10230             return ParserResult::ok(ParseResultType::Matched);
10231         };
10232         auto const setWaitForKeypress = [&](std::string const& keypress) {
10233             auto keypressLc = toLower(keypress);
10234             if (keypressLc == "never")
10235                 config.waitForKeypress = WaitForKeypress::Never;
10236             else if (keypressLc == "start")
10237                 config.waitForKeypress = WaitForKeypress::BeforeStart;
10238             else if (keypressLc == "exit")
10239                 config.waitForKeypress = WaitForKeypress::BeforeExit;
10240             else if (keypressLc == "both")
10241                 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
10242             else
10243                 return ParserResult::runtimeError(
10244                     "keypress argument must be one of: never, start, exit or "
10245                     "both. '" +
10246                     keypress + "' not recognised");
10247             return ParserResult::ok(ParseResultType::Matched);
10248         };
10249         auto const setVerbosity = [&](std::string const& verbosity) {
10250             auto lcVerbosity = toLower(verbosity);
10251             if (lcVerbosity == "quiet")
10252                 config.verbosity = Verbosity::Quiet;
10253             else if (lcVerbosity == "normal")
10254                 config.verbosity = Verbosity::Normal;
10255             else if (lcVerbosity == "high")
10256                 config.verbosity = Verbosity::High;
10257             else
10258                 return ParserResult::runtimeError("Unrecognised verbosity, '" + verbosity + "'");
10259             return ParserResult::ok(ParseResultType::Matched);
10260         };
10261         auto const setReporter = [&](std::string const& reporter) {
10262             IReporterRegistry::FactoryMap const& factories =
10263                 getRegistryHub().getReporterRegistry().getFactories();
10264
10265             auto lcReporter = toLower(reporter);
10266             auto result = factories.find(lcReporter);
10267
10268             if (factories.end() != result)
10269                 config.reporterName = lcReporter;
10270             else
10271                 return ParserResult::runtimeError("Unrecognized reporter, '" + reporter +
10272                                                   "'. Check available with --list-reporters");
10273             return ParserResult::ok(ParseResultType::Matched);
10274         };
10275
10276         auto cli =
10277             ExeName(config.processName) | Help(config.showHelp) |
10278             Opt(config.listTests)["-l"]["--list-tests"]("list all/matching test cases") |
10279             Opt(config.listTags)["-t"]["--list-tags"]("list all/matching tags") |
10280             Opt(config.showSuccessfulTests)["-s"]["--success"](
10281                 "include successful tests in output") |
10282             Opt(config.shouldDebugBreak)["-b"]["--break"]("break into debugger on failure") |
10283             Opt(config.noThrow)["-e"]["--nothrow"]("skip exception tests") |
10284             Opt(config.showInvisibles)["-i"]["--invisibles"]("show invisibles (tabs, newlines)") |
10285             Opt(config.outputFilename, "filename")["-o"]["--out"]("output filename") |
10286             Opt(setReporter, "name")["-r"]["--reporter"]("reporter to use (defaults to console)") |
10287             Opt(config.name, "name")["-n"]["--name"]("suite name") |
10288             Opt([&](bool) { config.abortAfter = 1; })["-a"]["--abort"]("abort at first failure") |
10289             Opt([&](int x) { config.abortAfter = x; },
10290                 "no. failures")["-x"]["--abortx"]("abort after x failures") |
10291             Opt(setWarning, "warning name")["-w"]["--warn"]("enable warnings") |
10292             Opt(
10293                 [&](bool flag) {
10294                     config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never;
10295                 },
10296                 "yes|no")["-d"]["--durations"]("show test durations") |
10297             Opt(config.minDuration, "seconds")["-D"]["--min-duration"](
10298                 "show test durations for tests taking at least the given "
10299                 "number of seconds") |
10300             Opt(loadTestNamesFromFile,
10301                 "filename")["-f"]["--input-file"]("load test names to run from a file") |
10302             Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"](
10303                 "adds a tag for the filename") |
10304             Opt(config.sectionsToRun, "section name")["-c"]["--section"]("specify section to run") |
10305             Opt(setVerbosity, "quiet|normal|high")["-v"]["--verbosity"]("set output verbosity") |
10306             Opt(config.listTestNamesOnly)["--list-test-names-only"](
10307                 "list all/matching test cases names only") |
10308             Opt(config.listReporters)["--list-reporters"]("list all reporters") |
10309             Opt(setTestOrder, "decl|lex|rand")["--order"]("test case order (defaults to decl)") |
10310             Opt(setRngSeed,
10311                 "'time'|number")["--rng-seed"]("set a specific seed for random numbers") |
10312             Opt(setColourUsage, "yes|no")["--use-colour"]("should output be colourised") |
10313             Opt(config.libIdentify)["--libidentify"](
10314                 "report name and version according to libidentify standard") |
10315             Opt(setWaitForKeypress, "never|start|exit|both")["--wait-for-keypress"](
10316                 "waits for a keypress before exiting") |
10317             Opt(config.benchmarkSamples,
10318                 "samples")["--benchmark-samples"]("number of samples to collect (default: 100)") |
10319             Opt(config.benchmarkResamples, "resamples")["--benchmark-resamples"](
10320                 "number of resamples for the bootstrap (default: 100000)") |
10321             Opt(config.benchmarkConfidenceInterval,
10322                 "confidence interval")["--benchmark-confidence-interval"](
10323                 "confidence interval for the bootstrap (between 0 and 1, "
10324                 "default: 0.95)") |
10325             Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"](
10326                 "perform only measurements; do not perform any analysis") |
10327             Opt(config.benchmarkWarmupTime, "benchmarkWarmupTime")["--benchmark-warmup-time"](
10328                 "amount of time in milliseconds spent on warming up each test "
10329                 "(default: 100)") |
10330             Arg(config.testsOrTags, "test name|pattern|tags")("which test or tests to use");
10331
10332         return cli;
10333     }
10334
10335 } // end namespace Catch
10336 // end catch_commandline.cpp
10337 // start catch_common.cpp
10338
10339 #include <cstring>
10340 #include <ostream>
10341
10342 namespace Catch {
10343
10344     bool SourceLineInfo::operator==(SourceLineInfo const& other) const noexcept {
10345         return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
10346     }
10347     bool SourceLineInfo::operator<(SourceLineInfo const& other) const noexcept {
10348         // We can assume that the same file will usually have the same pointer.
10349         // Thus, if the pointers are the same, there is no point in calling the
10350         // strcmp
10351         return line < other.line ||
10352                (line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
10353     }
10354
10355     std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info) {
10356 #ifndef __GNUG__
10357         os << info.file << '(' << info.line << ')';
10358 #else
10359         os << info.file << ':' << info.line;
10360 #endif
10361         return os;
10362     }
10363
10364     std::string StreamEndStop::operator+() const { return std::string(); }
10365
10366     NonCopyable::NonCopyable() = default;
10367     NonCopyable::~NonCopyable() = default;
10368
10369 } // namespace Catch
10370 // end catch_common.cpp
10371 // start catch_config.cpp
10372
10373 namespace Catch {
10374
10375     Config::Config(ConfigData const& data) : m_data(data), m_stream(openStream()) {
10376         // We need to trim filter specs to avoid trouble with superfluous
10377         // whitespace (esp. important for bdd macros, as those are manually
10378         // aligned with whitespace).
10379
10380         for (auto& elem : m_data.testsOrTags) {
10381             elem = trim(elem);
10382         }
10383         for (auto& elem : m_data.sectionsToRun) {
10384             elem = trim(elem);
10385         }
10386
10387         TestSpecParser parser(ITagAliasRegistry::get());
10388         if (!m_data.testsOrTags.empty()) {
10389             m_hasTestFilters = true;
10390             for (auto const& testOrTags : m_data.testsOrTags) {
10391                 parser.parse(testOrTags);
10392             }
10393         }
10394         m_testSpec = parser.testSpec();
10395     }
10396
10397     std::string const& Config::getFilename() const { return m_data.outputFilename; }
10398
10399     bool Config::listTests() const { return m_data.listTests; }
10400     bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
10401     bool Config::listTags() const { return m_data.listTags; }
10402     bool Config::listReporters() const { return m_data.listReporters; }
10403
10404     std::string Config::getProcessName() const { return m_data.processName; }
10405     std::string const& Config::getReporterName() const { return m_data.reporterName; }
10406
10407     std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
10408     std::vector<std::string> const& Config::getSectionsToRun() const {
10409         return m_data.sectionsToRun;
10410     }
10411
10412     TestSpec const& Config::testSpec() const { return m_testSpec; }
10413     bool Config::hasTestFilters() const { return m_hasTestFilters; }
10414
10415     bool Config::showHelp() const { return m_data.showHelp; }
10416
10417     // IConfig interface
10418     bool Config::allowThrows() const { return !m_data.noThrow; }
10419     std::ostream& Config::stream() const { return m_stream->stream(); }
10420     std::string Config::name() const {
10421         return m_data.name.empty() ? m_data.processName : m_data.name;
10422     }
10423     bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
10424     bool Config::warnAboutMissingAssertions() const {
10425         return !!(m_data.warnings & WarnAbout::NoAssertions);
10426     }
10427     bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
10428     ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
10429     double Config::minDuration() const { return m_data.minDuration; }
10430     RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
10431     unsigned int Config::rngSeed() const { return m_data.rngSeed; }
10432     UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
10433     bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10434     int Config::abortAfter() const { return m_data.abortAfter; }
10435     bool Config::showInvisibles() const { return m_data.showInvisibles; }
10436     Verbosity Config::verbosity() const { return m_data.verbosity; }
10437
10438     bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10439     int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10440     double Config::benchmarkConfidenceInterval() const {
10441         return m_data.benchmarkConfidenceInterval;
10442     }
10443     unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10444     std::chrono::milliseconds Config::benchmarkWarmupTime() const {
10445         return std::chrono::milliseconds(m_data.benchmarkWarmupTime);
10446     }
10447
10448     IStream const* Config::openStream() { return Catch::makeStream(m_data.outputFilename); }
10449
10450 } // end namespace Catch
10451 // end catch_config.cpp
10452 // start catch_console_colour.cpp
10453
10454 #if defined(__clang__)
10455 #pragma clang diagnostic push
10456 #pragma clang diagnostic ignored "-Wexit-time-destructors"
10457 #endif
10458
10459 // start catch_errno_guard.h
10460
10461 namespace Catch {
10462
10463     class ErrnoGuard {
10464     public:
10465         ErrnoGuard();
10466         ~ErrnoGuard();
10467
10468     private:
10469         int m_oldErrno;
10470     };
10471
10472 } // namespace Catch
10473
10474 // end catch_errno_guard.h
10475 // start catch_windows_h_proxy.h
10476
10477 #if defined(CATCH_PLATFORM_WINDOWS)
10478
10479 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10480 #define CATCH_DEFINED_NOMINMAX
10481 #define NOMINMAX
10482 #endif
10483 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10484 #define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10485 #define WIN32_LEAN_AND_MEAN
10486 #endif
10487
10488 #ifdef __AFXDLL
10489 #include <AfxWin.h>
10490 #else
10491 #include <windows.h>
10492 #endif
10493
10494 #ifdef CATCH_DEFINED_NOMINMAX
10495 #undef NOMINMAX
10496 #endif
10497 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10498 #undef WIN32_LEAN_AND_MEAN
10499 #endif
10500
10501 #endif // defined(CATCH_PLATFORM_WINDOWS)
10502
10503 // end catch_windows_h_proxy.h
10504 #include <sstream>
10505
10506 namespace Catch {
10507     namespace {
10508
10509         struct IColourImpl {
10510             virtual ~IColourImpl() = default;
10511             virtual void use(Colour::Code _colourCode) = 0;
10512         };
10513
10514         struct NoColourImpl : IColourImpl {
10515             void use(Colour::Code) override {}
10516
10517             static IColourImpl* instance() {
10518                 static NoColourImpl s_instance;
10519                 return &s_instance;
10520             }
10521         };
10522
10523     } // namespace
10524 } // namespace Catch
10525
10526 #if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) &&                 \
10527     !defined(CATCH_CONFIG_COLOUR_ANSI)
10528 #ifdef CATCH_PLATFORM_WINDOWS
10529 #define CATCH_CONFIG_COLOUR_WINDOWS
10530 #else
10531 #define CATCH_CONFIG_COLOUR_ANSI
10532 #endif
10533 #endif
10534
10535 #if defined(CATCH_CONFIG_COLOUR_WINDOWS) /////////////////////////////////////////
10536
10537 namespace Catch {
10538     namespace {
10539
10540         class Win32ColourImpl : public IColourImpl {
10541         public:
10542             Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) {
10543                 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10544                 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
10545                 originalForegroundAttributes =
10546                     csbiInfo.wAttributes &
10547                     ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
10548                 originalBackgroundAttributes =
10549                     csbiInfo.wAttributes &
10550                     ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
10551             }
10552
10553             void use(Colour::Code _colourCode) override {
10554                 switch (_colourCode) {
10555                     case Colour::None:
10556                         return setTextAttribute(originalForegroundAttributes);
10557                     case Colour::White:
10558                         return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED |
10559                                                 FOREGROUND_BLUE);
10560                     case Colour::Red:
10561                         return setTextAttribute(FOREGROUND_RED);
10562                     case Colour::Green:
10563                         return setTextAttribute(FOREGROUND_GREEN);
10564                     case Colour::Blue:
10565                         return setTextAttribute(FOREGROUND_BLUE);
10566                     case Colour::Cyan:
10567                         return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN);
10568                     case Colour::Yellow:
10569                         return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN);
10570                     case Colour::Grey:
10571                         return setTextAttribute(0);
10572
10573                     case Colour::LightGrey:
10574                         return setTextAttribute(FOREGROUND_INTENSITY);
10575                     case Colour::BrightRed:
10576                         return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED);
10577                     case Colour::BrightGreen:
10578                         return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
10579                     case Colour::BrightWhite:
10580                         return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN |
10581                                                 FOREGROUND_RED | FOREGROUND_BLUE);
10582                     case Colour::BrightYellow:
10583                         return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED |
10584                                                 FOREGROUND_GREEN);
10585
10586                     case Colour::Bright:
10587                         CATCH_INTERNAL_ERROR("not a colour");
10588
10589                     default:
10590                         CATCH_ERROR("Unknown colour requested");
10591                 }
10592             }
10593
10594         private:
10595             void setTextAttribute(WORD _textAttribute) {
10596                 SetConsoleTextAttribute(stdoutHandle,
10597                                         _textAttribute | originalBackgroundAttributes);
10598             }
10599             HANDLE stdoutHandle;
10600             WORD originalForegroundAttributes;
10601             WORD originalBackgroundAttributes;
10602         };
10603
10604         IColourImpl* platformColourInstance() {
10605             static Win32ColourImpl s_instance;
10606
10607             IConfigPtr config = getCurrentContext().getConfig();
10608             UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10609             if (colourMode == UseColour::Auto)
10610                 colourMode = UseColour::Yes;
10611             return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance();
10612         }
10613
10614     } // namespace
10615 } // end namespace Catch
10616
10617 #elif defined(CATCH_CONFIG_COLOUR_ANSI) //////////////////////////////////////
10618
10619 #include <unistd.h>
10620
10621 namespace Catch {
10622     namespace {
10623
10624         // use POSIX/ ANSI console terminal codes
10625         // Thanks to Adam Strzelecki for original contribution
10626         // (http://github.com/nanoant)
10627         // https://github.com/philsquared/Catch/pull/131
10628         class PosixColourImpl : public IColourImpl {
10629         public:
10630             void use(Colour::Code _colourCode) override {
10631                 switch (_colourCode) {
10632                     case Colour::None:
10633                     case Colour::White:
10634                         return setColour("[0m");
10635                     case Colour::Red:
10636                         return setColour("[0;31m");
10637                     case Colour::Green:
10638                         return setColour("[0;32m");
10639                     case Colour::Blue:
10640                         return setColour("[0;34m");
10641                     case Colour::Cyan:
10642                         return setColour("[0;36m");
10643                     case Colour::Yellow:
10644                         return setColour("[0;33m");
10645                     case Colour::Grey:
10646                         return setColour("[1;30m");
10647
10648                     case Colour::LightGrey:
10649                         return setColour("[0;37m");
10650                     case Colour::BrightRed:
10651                         return setColour("[1;31m");
10652                     case Colour::BrightGreen:
10653                         return setColour("[1;32m");
10654                     case Colour::BrightWhite:
10655                         return setColour("[1;37m");
10656                     case Colour::BrightYellow:
10657                         return setColour("[1;33m");
10658
10659                     case Colour::Bright:
10660                         CATCH_INTERNAL_ERROR("not a colour");
10661                     default:
10662                         CATCH_INTERNAL_ERROR("Unknown colour requested");
10663                 }
10664             }
10665             static IColourImpl* instance() {
10666                 static PosixColourImpl s_instance;
10667                 return &s_instance;
10668             }
10669
10670         private:
10671             void setColour(const char* _escapeCode) {
10672                 getCurrentContext().getConfig()->stream() << '\033' << _escapeCode;
10673             }
10674         };
10675
10676         bool useColourOnPlatform() {
10677             return
10678 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10679                 !isDebuggerActive() &&
10680 #endif
10681 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10682                 isatty(STDOUT_FILENO)
10683 #else
10684                 false
10685 #endif
10686                     ;
10687         }
10688         IColourImpl* platformColourInstance() {
10689             ErrnoGuard guard;
10690             IConfigPtr config = getCurrentContext().getConfig();
10691             UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10692             if (colourMode == UseColour::Auto)
10693                 colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No;
10694             return colourMode == UseColour::Yes ? PosixColourImpl::instance()
10695                                                 : NoColourImpl::instance();
10696         }
10697
10698     } // namespace
10699 } // end namespace Catch
10700
10701 #else // not Windows or ANSI ///////////////////////////////////////////////
10702
10703 namespace Catch {
10704
10705     static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10706
10707 } // end namespace Catch
10708
10709 #endif // Windows/ ANSI/ None
10710
10711 namespace Catch {
10712
10713     Colour::Colour(Code _colourCode) { use(_colourCode); }
10714     Colour::Colour(Colour&& other) noexcept {
10715         m_moved = other.m_moved;
10716         other.m_moved = true;
10717     }
10718     Colour& Colour::operator=(Colour&& other) noexcept {
10719         m_moved = other.m_moved;
10720         other.m_moved = true;
10721         return *this;
10722     }
10723
10724     Colour::~Colour() {
10725         if (!m_moved)
10726             use(None);
10727     }
10728
10729     void Colour::use(Code _colourCode) {
10730         static IColourImpl* impl = platformColourInstance();
10731         // Strictly speaking, this cannot possibly happen.
10732         // However, under some conditions it does happen (see #1626),
10733         // and this change is small enough that we can let practicality
10734         // triumph over purity in this case.
10735         if (impl != nullptr) {
10736             impl->use(_colourCode);
10737         }
10738     }
10739
10740     std::ostream& operator<<(std::ostream& os, Colour const&) { return os; }
10741
10742 } // end namespace Catch
10743
10744 #if defined(__clang__)
10745 #pragma clang diagnostic pop
10746 #endif
10747
10748 // end catch_console_colour.cpp
10749 // start catch_context.cpp
10750
10751 namespace Catch {
10752
10753     class Context : public IMutableContext, NonCopyable {
10754
10755     public: // IContext
10756         IResultCapture* getResultCapture() override { return m_resultCapture; }
10757         IRunner* getRunner() override { return m_runner; }
10758
10759         IConfigPtr const& getConfig() const override { return m_config; }
10760
10761         ~Context() override;
10762
10763     public: // IMutableContext
10764         void setResultCapture(IResultCapture* resultCapture) override {
10765             m_resultCapture = resultCapture;
10766         }
10767         void setRunner(IRunner* runner) override { m_runner = runner; }
10768         void setConfig(IConfigPtr const& config) override { m_config = config; }
10769
10770         friend IMutableContext& getCurrentMutableContext();
10771
10772     private:
10773         IConfigPtr m_config;
10774         IRunner* m_runner = nullptr;
10775         IResultCapture* m_resultCapture = nullptr;
10776     };
10777
10778     IMutableContext* IMutableContext::currentContext = nullptr;
10779
10780     void IMutableContext::createContext() { currentContext = new Context(); }
10781
10782     void cleanUpContext() {
10783         delete IMutableContext::currentContext;
10784         IMutableContext::currentContext = nullptr;
10785     }
10786     IContext::~IContext() = default;
10787     IMutableContext::~IMutableContext() = default;
10788     Context::~Context() = default;
10789
10790     SimplePcg32& rng() {
10791         static SimplePcg32 s_rng;
10792         return s_rng;
10793     }
10794
10795 } // namespace Catch
10796 // end catch_context.cpp
10797 // start catch_debug_console.cpp
10798
10799 // start catch_debug_console.h
10800
10801 #include <string>
10802
10803 namespace Catch {
10804     void writeToDebugConsole(std::string const& text);
10805 }
10806
10807 // end catch_debug_console.h
10808 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10809 #include <android/log.h>
10810
10811 namespace Catch {
10812     void writeToDebugConsole(std::string const& text) {
10813         __android_log_write(ANDROID_LOG_DEBUG, "Catch", text.c_str());
10814     }
10815 } // namespace Catch
10816
10817 #elif defined(CATCH_PLATFORM_WINDOWS)
10818
10819 namespace Catch {
10820     void writeToDebugConsole(std::string const& text) { ::OutputDebugStringA(text.c_str()); }
10821 } // namespace Catch
10822
10823 #else
10824
10825 namespace Catch {
10826     void writeToDebugConsole(std::string const& text) {
10827         // !TBD: Need a version for Mac/ XCode and other IDEs
10828         Catch::cout() << text;
10829     }
10830 } // namespace Catch
10831
10832 #endif // Platform
10833 // end catch_debug_console.cpp
10834 // start catch_debugger.cpp
10835
10836 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10837
10838 #include <cassert>
10839 #include <sys/types.h>
10840 #include <unistd.h>
10841 #include <cstddef>
10842 #include <ostream>
10843
10844 #ifdef __apple_build_version__
10845 // These headers will only compile with AppleClang (XCode)
10846 // For other compilers (Clang, GCC, ... ) we need to exclude them
10847 #include <sys/sysctl.h>
10848 #endif
10849
10850 namespace Catch {
10851 #ifdef __apple_build_version__
10852     // The following function is taken directly from the following technical
10853     // note: https://developer.apple.com/library/archive/qa/qa1361/_index.html
10854
10855     // Returns true if the current process is being debugged (either
10856     // running under the debugger or has a debugger attached post facto).
10857     bool isDebuggerActive() {
10858         int mib[4];
10859         struct kinfo_proc info;
10860         std::size_t size;
10861
10862         // Initialize the flags so that, if sysctl fails for some bizarre
10863         // reason, we get a predictable result.
10864
10865         info.kp_proc.p_flag = 0;
10866
10867         // Initialize mib, which tells sysctl the info we want, in this case
10868         // we're looking for information about a specific process ID.
10869
10870         mib[0] = CTL_KERN;
10871         mib[1] = KERN_PROC;
10872         mib[2] = KERN_PROC_PID;
10873         mib[3] = getpid();
10874
10875         // Call sysctl.
10876
10877         size = sizeof(info);
10878         if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0) {
10879             Catch::cerr() << "\n** Call to sysctl failed - unable to determine "
10880                              "if debugger is active **\n"
10881                           << std::endl;
10882             return false;
10883         }
10884
10885         // We're being debugged if the P_TRACED flag is set.
10886
10887         return ((info.kp_proc.p_flag & P_TRACED) != 0);
10888     }
10889 #else
10890     bool isDebuggerActive() {
10891         // We need to find another way to determine this for non-appleclang
10892         // compilers on macOS
10893         return false;
10894     }
10895 #endif
10896 } // namespace Catch
10897
10898 #elif defined(CATCH_PLATFORM_LINUX)
10899 #include <fstream>
10900 #include <string>
10901
10902 namespace Catch {
10903     // The standard POSIX way of detecting a debugger is to attempt to
10904     // ptrace() the process, but this needs to be done from a child and not
10905     // this process itself to still allow attaching to this process later
10906     // if wanted, so is rather heavy. Under Linux we have the PID of the
10907     // "debugger" (which doesn't need to be gdb, of course, it could also
10908     // be strace, for example) in /proc/$PID/status, so just get it from
10909     // there instead.
10910     bool isDebuggerActive() {
10911         // Libstdc++ has a bug, where std::ifstream sets errno to 0
10912         // This way our users can properly assert over errno values
10913         ErrnoGuard guard;
10914         std::ifstream in("/proc/self/status");
10915         for (std::string line; std::getline(in, line);) {
10916             static const int PREFIX_LEN = 11;
10917             if (line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0) {
10918                 // We're traced if the PID is not 0 and no other PID starts
10919                 // with 0 digit, so it's enough to check for just a single
10920                 // character.
10921                 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10922             }
10923         }
10924
10925         return false;
10926     }
10927 } // namespace Catch
10928 #elif defined(_MSC_VER)
10929 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10930 namespace Catch {
10931     bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
10932 } // namespace Catch
10933 #elif defined(__MINGW32__)
10934 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10935 namespace Catch {
10936     bool isDebuggerActive() { return IsDebuggerPresent() != 0; }
10937 } // namespace Catch
10938 #else
10939 namespace Catch {
10940     bool isDebuggerActive() { return false; }
10941 } // namespace Catch
10942 #endif // Platform
10943 // end catch_debugger.cpp
10944 // start catch_decomposer.cpp
10945
10946 namespace Catch {
10947
10948     ITransientExpression::~ITransientExpression() = default;
10949
10950     void formatReconstructedExpression(std::ostream& os,
10951                                        std::string const& lhs,
10952                                        StringRef op,
10953                                        std::string const& rhs) {
10954         if (lhs.size() + rhs.size() < 40 && lhs.find('\n') == std::string::npos &&
10955             rhs.find('\n') == std::string::npos)
10956             os << lhs << " " << op << " " << rhs;
10957         else
10958             os << lhs << "\n" << op << "\n" << rhs;
10959     }
10960 } // namespace Catch
10961 // end catch_decomposer.cpp
10962 // start catch_enforce.cpp
10963
10964 #include <stdexcept>
10965
10966 namespace Catch {
10967 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) &&                                                    \
10968     !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10969     [[noreturn]] void throw_exception(std::exception const& e) {
10970         Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10971                       << "The message was: " << e.what() << '\n';
10972         std::terminate();
10973     }
10974 #endif
10975
10976     [[noreturn]] void throw_logic_error(std::string const& msg) {
10977         throw_exception(std::logic_error(msg));
10978     }
10979
10980     [[noreturn]] void throw_domain_error(std::string const& msg) {
10981         throw_exception(std::domain_error(msg));
10982     }
10983
10984     [[noreturn]] void throw_runtime_error(std::string const& msg) {
10985         throw_exception(std::runtime_error(msg));
10986     }
10987
10988 } // namespace Catch
10989 // end catch_enforce.cpp
10990 // start catch_enum_values_registry.cpp
10991 // start catch_enum_values_registry.h
10992
10993 #include <vector>
10994 #include <memory>
10995
10996 namespace Catch {
10997
10998     namespace Detail {
10999
11000         std::unique_ptr<EnumInfo>
11001         makeEnumInfo(StringRef enumName, StringRef allValueNames, std::vector<int> const& values);
11002
11003         class EnumValuesRegistry : public IMutableEnumValuesRegistry {
11004
11005             std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
11006
11007             EnumInfo const& registerEnum(StringRef enumName,
11008                                          StringRef allEnums,
11009                                          std::vector<int> const& values) override;
11010         };
11011
11012         std::vector<StringRef> parseEnums(StringRef enums);
11013
11014     } // namespace Detail
11015
11016 } // namespace Catch
11017
11018 // end catch_enum_values_registry.h
11019
11020 #include <map>
11021 #include <cassert>
11022
11023 namespace Catch {
11024
11025     IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
11026
11027     namespace Detail {
11028
11029         namespace {
11030             // Extracts the actual name part of an enum instance
11031             // In other words, it returns the Blue part of
11032             // Bikeshed::Colour::Blue
11033             StringRef extractInstanceName(StringRef enumInstance) {
11034                 // Find last occurrence of ":"
11035                 size_t name_start = enumInstance.size();
11036                 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
11037                     --name_start;
11038                 }
11039                 return enumInstance.substr(name_start, enumInstance.size() - name_start);
11040             }
11041         } // namespace
11042
11043         std::vector<StringRef> parseEnums(StringRef enums) {
11044             auto enumValues = splitStringRef(enums, ',');
11045             std::vector<StringRef> parsed;
11046             parsed.reserve(enumValues.size());
11047             for (auto const& enumValue : enumValues) {
11048                 parsed.push_back(trim(extractInstanceName(enumValue)));
11049             }
11050             return parsed;
11051         }
11052
11053         EnumInfo::~EnumInfo() {}
11054
11055         StringRef EnumInfo::lookup(int value) const {
11056             for (auto const& valueToName : m_values) {
11057                 if (valueToName.first == value)
11058                     return valueToName.second;
11059             }
11060             return "{** unexpected enum value **}"_sr;
11061         }
11062
11063         std::unique_ptr<EnumInfo>
11064         makeEnumInfo(StringRef enumName, StringRef allValueNames, std::vector<int> const& values) {
11065             std::unique_ptr<EnumInfo> enumInfo(new EnumInfo);
11066             enumInfo->m_name = enumName;
11067             enumInfo->m_values.reserve(values.size());
11068
11069             const auto valueNames = Catch::Detail::parseEnums(allValueNames);
11070             assert(valueNames.size() == values.size());
11071             std::size_t i = 0;
11072             for (auto value : values)
11073                 enumInfo->m_values.emplace_back(value, valueNames[i++]);
11074
11075             return enumInfo;
11076         }
11077
11078         EnumInfo const& EnumValuesRegistry::registerEnum(StringRef enumName,
11079                                                          StringRef allValueNames,
11080                                                          std::vector<int> const& values) {
11081             m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
11082             return *m_enumInfos.back();
11083         }
11084
11085     } // namespace Detail
11086 } // namespace Catch
11087
11088 // end catch_enum_values_registry.cpp
11089 // start catch_errno_guard.cpp
11090
11091 #include <cerrno>
11092
11093 namespace Catch {
11094     ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {}
11095     ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
11096 } // namespace Catch
11097 // end catch_errno_guard.cpp
11098 // start catch_exception_translator_registry.cpp
11099
11100 // start catch_exception_translator_registry.h
11101
11102 #include <vector>
11103 #include <string>
11104 #include <memory>
11105
11106 namespace Catch {
11107
11108     class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
11109     public:
11110         ~ExceptionTranslatorRegistry();
11111         virtual void registerTranslator(const IExceptionTranslator* translator);
11112         std::string translateActiveException() const override;
11113         std::string tryTranslators() const;
11114
11115     private:
11116         std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
11117     };
11118 } // namespace Catch
11119
11120 // end catch_exception_translator_registry.h
11121 #ifdef __OBJC__
11122 #import "Foundation/Foundation.h"
11123 #endif
11124
11125 namespace Catch {
11126
11127     ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {}
11128
11129     void ExceptionTranslatorRegistry::registerTranslator(const IExceptionTranslator* translator) {
11130         m_translators.push_back(std::unique_ptr<const IExceptionTranslator>(translator));
11131     }
11132
11133 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
11134     std::string ExceptionTranslatorRegistry::translateActiveException() const {
11135         try {
11136 #ifdef __OBJC__
11137             // In Objective-C try objective-c exceptions first
11138             @try
11139             {
11140                 return tryTranslators();
11141             } @catch (NSException* exception)
11142             {
11143                 return Catch::Detail::stringify([exception description]);
11144             }
11145 #else
11146             // Compiling a mixed mode project with MSVC means that CLR
11147             // exceptions will be caught in (...) as well. However, these
11148             // do not fill-in std::current_exception and thus lead to crash
11149             // when attempting rethrow.
11150             // /EHa switch also causes structured exceptions to be caught
11151             // here, but they fill-in current_exception properly, so
11152             // at worst the output should be a little weird, instead of
11153             // causing a crash.
11154             if (std::current_exception() == nullptr) {
11155                 return "Non C++ exception. Possibly a CLR exception.";
11156             }
11157             return tryTranslators();
11158 #endif
11159         } catch (TestFailureException&) {
11160             std::rethrow_exception(std::current_exception());
11161         } catch (std::exception& ex) {
11162             return ex.what();
11163         } catch (std::string& msg) {
11164             return msg;
11165         } catch (const char* msg) {
11166             return msg;
11167         } catch (...) {
11168             return "Unknown exception";
11169         }
11170     }
11171
11172     std::string ExceptionTranslatorRegistry::tryTranslators() const {
11173         if (m_translators.empty()) {
11174             std::rethrow_exception(std::current_exception());
11175         } else {
11176             return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
11177         }
11178     }
11179
11180 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
11181     std::string ExceptionTranslatorRegistry::translateActiveException() const {
11182         CATCH_INTERNAL_ERROR("Attempted to translate active exception under "
11183                              "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11184     }
11185
11186     std::string ExceptionTranslatorRegistry::tryTranslators() const {
11187         CATCH_INTERNAL_ERROR("Attempted to use exception translators under "
11188                              "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
11189     }
11190 #endif
11191
11192 } // namespace Catch
11193 // end catch_exception_translator_registry.cpp
11194 // start catch_fatal_condition.cpp
11195
11196 #include <algorithm>
11197
11198 #if !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
11199
11200 namespace Catch {
11201
11202     // If neither SEH nor signal handling is required, the handler impls
11203     // do not have to do anything, and can be empty.
11204     void FatalConditionHandler::engage_platform() {}
11205     void FatalConditionHandler::disengage_platform() {}
11206     FatalConditionHandler::FatalConditionHandler() = default;
11207     FatalConditionHandler::~FatalConditionHandler() = default;
11208
11209 } // end namespace Catch
11210
11211 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
11212
11213 #if defined(CATCH_CONFIG_WINDOWS_SEH) && defined(CATCH_CONFIG_POSIX_SIGNALS)
11214 #error                                                                                             \
11215     "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
11216 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
11217
11218 #if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS)
11219
11220 namespace {
11221     //! Signals fatal error message to the run context
11222     void reportFatal(char const* const message) {
11223         Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition(message);
11224     }
11225
11226     //! Minimal size Catch2 needs for its own fatal error handling.
11227     //! Picked anecdotally, so it might not be sufficient on all
11228     //! platforms, and for all configurations.
11229     constexpr std::size_t minStackSizeForErrors = 32 * 1024;
11230 } // end unnamed namespace
11231
11232 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
11233
11234 #if defined(CATCH_CONFIG_WINDOWS_SEH)
11235
11236 namespace Catch {
11237
11238     struct SignalDefs {
11239         DWORD id;
11240         const char* name;
11241     };
11242
11243     // There is no 1-1 mapping between signals and windows exceptions.
11244     // Windows can easily distinguish between SO and SigSegV,
11245     // but SigInt, SigTerm, etc are handled differently.
11246     static SignalDefs signalDefs[] = {
11247         {static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal"},
11248         {static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow"},
11249         {static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal"},
11250         {static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error"},
11251     };
11252
11253     static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
11254         for (auto const& def : signalDefs) {
11255             if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
11256                 reportFatal(def.name);
11257             }
11258         }
11259         // If its not an exception we care about, pass it along.
11260         // This stops us from eating debugger breaks etc.
11261         return EXCEPTION_CONTINUE_SEARCH;
11262     }
11263
11264     // Since we do not support multiple instantiations, we put these
11265     // into global variables and rely on cleaning them up in outlined
11266     // constructors/destructors
11267     static PVOID exceptionHandlerHandle = nullptr;
11268
11269     // For MSVC, we reserve part of the stack memory for handling
11270     // memory overflow structured exception.
11271     FatalConditionHandler::FatalConditionHandler() {
11272         ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
11273         if (!SetThreadStackGuarantee(&guaranteeSize)) {
11274             // We do not want to fully error out, because needing
11275             // the stack reserve should be rare enough anyway.
11276             Catch::cerr() << "Failed to reserve piece of stack."
11277                           << " Stack overflows will not be reported successfully.";
11278         }
11279     }
11280
11281     // We do not attempt to unset the stack guarantee, because
11282     // Windows does not support lowering the stack size guarantee.
11283     FatalConditionHandler::~FatalConditionHandler() = default;
11284
11285     void FatalConditionHandler::engage_platform() {
11286         // Register as first handler in current chain
11287         exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
11288         if (!exceptionHandlerHandle) {
11289             CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
11290         }
11291     }
11292
11293     void FatalConditionHandler::disengage_platform() {
11294         if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
11295             CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
11296         }
11297         exceptionHandlerHandle = nullptr;
11298     }
11299
11300 } // end namespace Catch
11301
11302 #endif // CATCH_CONFIG_WINDOWS_SEH
11303
11304 #if defined(CATCH_CONFIG_POSIX_SIGNALS)
11305
11306 #include <signal.h>
11307
11308 namespace Catch {
11309
11310     struct SignalDefs {
11311         int id;
11312         const char* name;
11313     };
11314
11315     static SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"},
11316                                       {SIGILL, "SIGILL - Illegal instruction signal"},
11317                                       {SIGFPE, "SIGFPE - Floating point error signal"},
11318                                       {SIGSEGV, "SIGSEGV - Segmentation violation signal"},
11319                                       {SIGTERM, "SIGTERM - Termination request signal"},
11320                                       {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}};
11321
11322 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
11323 // which is zero initialization, but not explicit. We want to avoid
11324 // that.
11325 #if defined(__GNUC__)
11326 #pragma GCC diagnostic push
11327 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
11328 #endif
11329
11330     static char* altStackMem = nullptr;
11331     static std::size_t altStackSize = 0;
11332     static stack_t oldSigStack{};
11333     static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
11334
11335     static void restorePreviousSignalHandlers() {
11336         // We set signal handlers back to the previous ones. Hopefully
11337         // nobody overwrote them in the meantime, and doesn't expect
11338         // their signal handlers to live past ours given that they
11339         // installed them after ours..
11340         for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11341             sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
11342         }
11343         // Return the old stack
11344         sigaltstack(&oldSigStack, nullptr);
11345     }
11346
11347     static void handleSignal(int sig) {
11348         char const* name = "<unknown signal>";
11349         for (auto const& def : signalDefs) {
11350             if (sig == def.id) {
11351                 name = def.name;
11352                 break;
11353             }
11354         }
11355         // We need to restore previous signal handlers and let them do
11356         // their thing, so that the users can have the debugger break
11357         // when a signal is raised, and so on.
11358         restorePreviousSignalHandlers();
11359         reportFatal(name);
11360         raise(sig);
11361     }
11362
11363     FatalConditionHandler::FatalConditionHandler() {
11364         assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
11365         if (altStackSize == 0) {
11366             altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
11367         }
11368         altStackMem = new char[altStackSize]();
11369     }
11370
11371     FatalConditionHandler::~FatalConditionHandler() {
11372         delete[] altStackMem;
11373         // We signal that another instance can be constructed by zeroing
11374         // out the pointer.
11375         altStackMem = nullptr;
11376     }
11377
11378     void FatalConditionHandler::engage_platform() {
11379         stack_t sigStack;
11380         sigStack.ss_sp = altStackMem;
11381         sigStack.ss_size = altStackSize;
11382         sigStack.ss_flags = 0;
11383         sigaltstack(&sigStack, &oldSigStack);
11384         struct sigaction sa = {};
11385
11386         sa.sa_handler = handleSignal;
11387         sa.sa_flags = SA_ONSTACK;
11388         for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
11389             sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
11390         }
11391     }
11392
11393 #if defined(__GNUC__)
11394 #pragma GCC diagnostic pop
11395 #endif
11396
11397     void FatalConditionHandler::disengage_platform() { restorePreviousSignalHandlers(); }
11398
11399 } // end namespace Catch
11400
11401 #endif // CATCH_CONFIG_POSIX_SIGNALS
11402 // end catch_fatal_condition.cpp
11403 // start catch_generators.cpp
11404
11405 #include <limits>
11406 #include <set>
11407
11408 namespace Catch {
11409
11410     IGeneratorTracker::~IGeneratorTracker() {}
11411
11412     const char* GeneratorException::what() const noexcept { return m_msg; }
11413
11414     namespace Generators {
11415
11416         GeneratorUntypedBase::~GeneratorUntypedBase() {}
11417
11418         auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo const& lineInfo)
11419             -> IGeneratorTracker& {
11420             return getResultCapture().acquireGeneratorTracker(generatorName, lineInfo);
11421         }
11422
11423     } // namespace Generators
11424 } // namespace Catch
11425 // end catch_generators.cpp
11426 // start catch_interfaces_capture.cpp
11427
11428 namespace Catch {
11429     IResultCapture::~IResultCapture() = default;
11430 }
11431 // end catch_interfaces_capture.cpp
11432 // start catch_interfaces_config.cpp
11433
11434 namespace Catch {
11435     IConfig::~IConfig() = default;
11436 }
11437 // end catch_interfaces_config.cpp
11438 // start catch_interfaces_exception.cpp
11439
11440 namespace Catch {
11441     IExceptionTranslator::~IExceptionTranslator() = default;
11442     IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11443 } // namespace Catch
11444 // end catch_interfaces_exception.cpp
11445 // start catch_interfaces_registry_hub.cpp
11446
11447 namespace Catch {
11448     IRegistryHub::~IRegistryHub() = default;
11449     IMutableRegistryHub::~IMutableRegistryHub() = default;
11450 } // namespace Catch
11451 // end catch_interfaces_registry_hub.cpp
11452 // start catch_interfaces_reporter.cpp
11453
11454 // start catch_reporter_listening.h
11455
11456 namespace Catch {
11457
11458     class ListeningReporter : public IStreamingReporter {
11459         using Reporters = std::vector<IStreamingReporterPtr>;
11460         Reporters m_listeners;
11461         IStreamingReporterPtr m_reporter = nullptr;
11462         ReporterPreferences m_preferences;
11463
11464     public:
11465         ListeningReporter();
11466
11467         void addListener(IStreamingReporterPtr&& listener);
11468         void addReporter(IStreamingReporterPtr&& reporter);
11469
11470     public: // IStreamingReporter
11471         ReporterPreferences getPreferences() const override;
11472
11473         void noMatchingTestCases(std::string const& spec) override;
11474
11475         void reportInvalidArguments(std::string const& arg) override;
11476
11477         static std::set<Verbosity> getSupportedVerbosities();
11478
11479 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11480         void benchmarkPreparing(std::string const& name) override;
11481         void benchmarkStarting(BenchmarkInfo const& benchmarkInfo) override;
11482         void benchmarkEnded(BenchmarkStats<> const& benchmarkStats) override;
11483         void benchmarkFailed(std::string const&) override;
11484 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11485
11486         void testRunStarting(TestRunInfo const& testRunInfo) override;
11487         void testGroupStarting(GroupInfo const& groupInfo) override;
11488         void testCaseStarting(TestCaseInfo const& testInfo) override;
11489         void sectionStarting(SectionInfo const& sectionInfo) override;
11490         void assertionStarting(AssertionInfo const& assertionInfo) override;
11491
11492         // The return value indicates if the messages buffer should be cleared:
11493         bool assertionEnded(AssertionStats const& assertionStats) override;
11494         void sectionEnded(SectionStats const& sectionStats) override;
11495         void testCaseEnded(TestCaseStats const& testCaseStats) override;
11496         void testGroupEnded(TestGroupStats const& testGroupStats) override;
11497         void testRunEnded(TestRunStats const& testRunStats) override;
11498
11499         void skipTest(TestCaseInfo const& testInfo) override;
11500         bool isMulti() const override;
11501     };
11502
11503 } // end namespace Catch
11504
11505 // end catch_reporter_listening.h
11506 namespace Catch {
11507
11508     ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig) :
11509         m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig) {}
11510
11511     ReporterConfig::ReporterConfig(IConfigPtr const& _fullConfig, std::ostream& _stream) :
11512         m_stream(&_stream), m_fullConfig(_fullConfig) {}
11513
11514     std::ostream& ReporterConfig::stream() const { return *m_stream; }
11515     IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11516
11517     TestRunInfo::TestRunInfo(std::string const& _name) : name(_name) {}
11518
11519     GroupInfo::GroupInfo(std::string const& _name,
11520                          std::size_t _groupIndex,
11521                          std::size_t _groupsCount) :
11522         name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount) {}
11523
11524     AssertionStats::AssertionStats(AssertionResult const& _assertionResult,
11525                                    std::vector<MessageInfo> const& _infoMessages,
11526                                    Totals const& _totals) :
11527         assertionResult(_assertionResult), infoMessages(_infoMessages), totals(_totals) {
11528         assertionResult.m_resultData.lazyExpression.m_transientExpression =
11529             _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11530
11531         if (assertionResult.hasMessage()) {
11532             // Copy message into messages list.
11533             // !TBD This should have been done earlier, somewhere
11534             MessageBuilder builder(assertionResult.getTestMacroName(),
11535                                    assertionResult.getSourceInfo(),
11536                                    assertionResult.getResultType());
11537             builder << assertionResult.getMessage();
11538             builder.m_info.message = builder.m_stream.str();
11539
11540             infoMessages.push_back(builder.m_info);
11541         }
11542     }
11543
11544     AssertionStats::~AssertionStats() = default;
11545
11546     SectionStats::SectionStats(SectionInfo const& _sectionInfo,
11547                                Counts const& _assertions,
11548                                double _durationInSeconds,
11549                                bool _missingAssertions) :
11550         sectionInfo(_sectionInfo),
11551         assertions(_assertions),
11552         durationInSeconds(_durationInSeconds),
11553         missingAssertions(_missingAssertions) {}
11554
11555     SectionStats::~SectionStats() = default;
11556
11557     TestCaseStats::TestCaseStats(TestCaseInfo const& _testInfo,
11558                                  Totals const& _totals,
11559                                  std::string const& _stdOut,
11560                                  std::string const& _stdErr,
11561                                  bool _aborting) :
11562         testInfo(_testInfo),
11563         totals(_totals),
11564         stdOut(_stdOut),
11565         stdErr(_stdErr),
11566         aborting(_aborting) {}
11567
11568     TestCaseStats::~TestCaseStats() = default;
11569
11570     TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo,
11571                                    Totals const& _totals,
11572                                    bool _aborting) :
11573         groupInfo(_groupInfo), totals(_totals), aborting(_aborting) {}
11574
11575     TestGroupStats::TestGroupStats(GroupInfo const& _groupInfo) :
11576         groupInfo(_groupInfo), aborting(false) {}
11577
11578     TestGroupStats::~TestGroupStats() = default;
11579
11580     TestRunStats::TestRunStats(TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting) :
11581         runInfo(_runInfo), totals(_totals), aborting(_aborting) {}
11582
11583     TestRunStats::~TestRunStats() = default;
11584
11585     void IStreamingReporter::fatalErrorEncountered(StringRef) {}
11586     bool IStreamingReporter::isMulti() const { return false; }
11587
11588     IReporterFactory::~IReporterFactory() = default;
11589     IReporterRegistry::~IReporterRegistry() = default;
11590
11591 } // end namespace Catch
11592 // end catch_interfaces_reporter.cpp
11593 // start catch_interfaces_runner.cpp
11594
11595 namespace Catch {
11596     IRunner::~IRunner() = default;
11597 }
11598 // end catch_interfaces_runner.cpp
11599 // start catch_interfaces_testcase.cpp
11600
11601 namespace Catch {
11602     ITestInvoker::~ITestInvoker() = default;
11603     ITestCaseRegistry::~ITestCaseRegistry() = default;
11604 } // namespace Catch
11605 // end catch_interfaces_testcase.cpp
11606 // start catch_leak_detector.cpp
11607
11608 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11609 #include <crtdbg.h>
11610
11611 namespace Catch {
11612
11613     LeakDetector::LeakDetector() {
11614         int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11615         flag |= _CRTDBG_LEAK_CHECK_DF;
11616         flag |= _CRTDBG_ALLOC_MEM_DF;
11617         _CrtSetDbgFlag(flag);
11618         _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11619         _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11620         // Change this to leaking allocation's number to break there
11621         _CrtSetBreakAlloc(-1);
11622     }
11623 } // namespace Catch
11624
11625 #else
11626
11627 Catch::LeakDetector::LeakDetector() {}
11628
11629 #endif
11630
11631 Catch::LeakDetector::~LeakDetector() { Catch::cleanUp(); }
11632 // end catch_leak_detector.cpp
11633 // start catch_list.cpp
11634
11635 // start catch_list.h
11636
11637 #include <set>
11638
11639 namespace Catch {
11640
11641     std::size_t listTests(Config const& config);
11642
11643     std::size_t listTestsNamesOnly(Config const& config);
11644
11645     struct TagInfo {
11646         void add(std::string const& spelling);
11647         std::string all() const;
11648
11649         std::set<std::string> spellings;
11650         std::size_t count = 0;
11651     };
11652
11653     std::size_t listTags(Config const& config);
11654
11655     std::size_t listReporters();
11656
11657     Option<std::size_t> list(std::shared_ptr<Config> const& config);
11658
11659 } // end namespace Catch
11660
11661 // end catch_list.h
11662 // start catch_text.h
11663
11664 namespace Catch {
11665     using namespace clara::TextFlow;
11666 }
11667
11668 // end catch_text.h
11669 #include <limits>
11670 #include <algorithm>
11671 #include <iomanip>
11672
11673 namespace Catch {
11674
11675     std::size_t listTests(Config const& config) {
11676         TestSpec const& testSpec = config.testSpec();
11677         if (config.hasTestFilters())
11678             Catch::cout() << "Matching test cases:\n";
11679         else {
11680             Catch::cout() << "All available test cases:\n";
11681         }
11682
11683         auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
11684         for (auto const& testCaseInfo : matchedTestCases) {
11685             Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None;
11686             Colour colourGuard(colour);
11687
11688             Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) << "\n";
11689             if (config.verbosity() >= Verbosity::High) {
11690                 Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4)
11691                               << std::endl;
11692                 std::string description = testCaseInfo.description;
11693                 if (description.empty())
11694                     description = "(NO DESCRIPTION)";
11695                 Catch::cout() << Column(description).indent(4) << std::endl;
11696             }
11697             if (!testCaseInfo.tags.empty())
11698                 Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) << "\n";
11699         }
11700
11701         if (!config.hasTestFilters())
11702             Catch::cout() << pluralise(matchedTestCases.size(), "test case") << '\n' << std::endl;
11703         else
11704             Catch::cout() << pluralise(matchedTestCases.size(), "matching test case") << '\n'
11705                           << std::endl;
11706         return matchedTestCases.size();
11707     }
11708
11709     std::size_t listTestsNamesOnly(Config const& config) {
11710         TestSpec const& testSpec = config.testSpec();
11711         std::size_t matchedTests = 0;
11712         std::vector<TestCase> matchedTestCases =
11713             filterTests(getAllTestCasesSorted(config), testSpec, config);
11714         for (auto const& testCaseInfo : matchedTestCases) {
11715             matchedTests++;
11716             if (startsWith(testCaseInfo.name, '#'))
11717                 Catch::cout() << '"' << testCaseInfo.name << '"';
11718             else
11719                 Catch::cout() << testCaseInfo.name;
11720             if (config.verbosity() >= Verbosity::High)
11721                 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11722             Catch::cout() << std::endl;
11723         }
11724         return matchedTests;
11725     }
11726
11727     void TagInfo::add(std::string const& spelling) {
11728         ++count;
11729         spellings.insert(spelling);
11730     }
11731
11732     std::string TagInfo::all() const {
11733         size_t size = 0;
11734         for (auto const& spelling : spellings) {
11735             // Add 2 for the brackes
11736             size += spelling.size() + 2;
11737         }
11738
11739         std::string out;
11740         out.reserve(size);
11741         for (auto const& spelling : spellings) {
11742             out += '[';
11743             out += spelling;
11744             out += ']';
11745         }
11746         return out;
11747     }
11748
11749     std::size_t listTags(Config const& config) {
11750         TestSpec const& testSpec = config.testSpec();
11751         if (config.hasTestFilters())
11752             Catch::cout() << "Tags for matching test cases:\n";
11753         else {
11754             Catch::cout() << "All available tags:\n";
11755         }
11756
11757         std::map<std::string, TagInfo> tagCounts;
11758
11759         std::vector<TestCase> matchedTestCases =
11760             filterTests(getAllTestCasesSorted(config), testSpec, config);
11761         for (auto const& testCase : matchedTestCases) {
11762             for (auto const& tagName : testCase.getTestCaseInfo().tags) {
11763                 std::string lcaseTagName = toLower(tagName);
11764                 auto countIt = tagCounts.find(lcaseTagName);
11765                 if (countIt == tagCounts.end())
11766                     countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first;
11767                 countIt->second.add(tagName);
11768             }
11769         }
11770
11771         for (auto const& tagCount : tagCounts) {
11772             ReusableStringStream rss;
11773             rss << "  " << std::setw(2) << tagCount.second.count << "  ";
11774             auto str = rss.str();
11775             auto wrapper = Column(tagCount.second.all())
11776                                .initialIndent(0)
11777                                .indent(str.size())
11778                                .width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
11779             Catch::cout() << str << wrapper << '\n';
11780         }
11781         Catch::cout() << pluralise(tagCounts.size(), "tag") << '\n' << std::endl;
11782         return tagCounts.size();
11783     }
11784
11785     std::size_t listReporters() {
11786         Catch::cout() << "Available reporters:\n";
11787         IReporterRegistry::FactoryMap const& factories =
11788             getRegistryHub().getReporterRegistry().getFactories();
11789         std::size_t maxNameLen = 0;
11790         for (auto const& factoryKvp : factories)
11791             maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size());
11792
11793         for (auto const& factoryKvp : factories) {
11794             Catch::cout() << Column(factoryKvp.first + ":").indent(2).width(5 + maxNameLen) +
11795                                  Column(factoryKvp.second->getDescription())
11796                                      .initialIndent(0)
11797                                      .indent(2)
11798                                      .width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
11799                           << "\n";
11800         }
11801         Catch::cout() << std::endl;
11802         return factories.size();
11803     }
11804
11805     Option<std::size_t> list(std::shared_ptr<Config> const& config) {
11806         Option<std::size_t> listedCount;
11807         getCurrentMutableContext().setConfig(config);
11808         if (config->listTests())
11809             listedCount = listedCount.valueOr(0) + listTests(*config);
11810         if (config->listTestNamesOnly())
11811             listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config);
11812         if (config->listTags())
11813             listedCount = listedCount.valueOr(0) + listTags(*config);
11814         if (config->listReporters())
11815             listedCount = listedCount.valueOr(0) + listReporters();
11816         return listedCount;
11817     }
11818
11819 } // end namespace Catch
11820 // end catch_list.cpp
11821 // start catch_matchers.cpp
11822
11823 namespace Catch {
11824     namespace Matchers {
11825         namespace Impl {
11826
11827             std::string MatcherUntypedBase::toString() const {
11828                 if (m_cachedToString.empty())
11829                     m_cachedToString = describe();
11830                 return m_cachedToString;
11831             }
11832
11833             MatcherUntypedBase::~MatcherUntypedBase() = default;
11834
11835         } // namespace Impl
11836     }     // namespace Matchers
11837
11838     using namespace Matchers;
11839     using Matchers::Impl::MatcherBase;
11840
11841 } // namespace Catch
11842 // end catch_matchers.cpp
11843 // start catch_matchers_exception.cpp
11844
11845 namespace Catch {
11846     namespace Matchers {
11847         namespace Exception {
11848
11849             bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11850                 return ex.what() == m_message;
11851             }
11852
11853             std::string ExceptionMessageMatcher::describe() const {
11854                 return "exception message matches \"" + m_message + "\"";
11855             }
11856
11857         } // namespace Exception
11858         Exception::ExceptionMessageMatcher Message(std::string const& message) {
11859             return Exception::ExceptionMessageMatcher(message);
11860         }
11861
11862         // namespace Exception
11863     } // namespace Matchers
11864 } // namespace Catch
11865 // end catch_matchers_exception.cpp
11866 // start catch_matchers_floating.cpp
11867
11868 // start catch_polyfills.hpp
11869
11870 namespace Catch {
11871     bool isnan(float f);
11872     bool isnan(double d);
11873 } // namespace Catch
11874
11875 // end catch_polyfills.hpp
11876 // start catch_to_string.hpp
11877
11878 #include <string>
11879
11880 namespace Catch {
11881     template <typename T> std::string to_string(T const& t) {
11882 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11883         return std::to_string(t);
11884 #else
11885         ReusableStringStream rss;
11886         rss << t;
11887         return rss.str();
11888 #endif
11889     }
11890 } // end namespace Catch
11891
11892 // end catch_to_string.hpp
11893 #include <algorithm>
11894 #include <cmath>
11895 #include <cstdlib>
11896 #include <cstdint>
11897 #include <cstring>
11898 #include <sstream>
11899 #include <type_traits>
11900 #include <iomanip>
11901 #include <limits>
11902
11903 namespace Catch {
11904     namespace {
11905
11906         int32_t convert(float f) {
11907             static_assert(sizeof(float) == sizeof(int32_t),
11908                           "Important ULP matcher assumption violated");
11909             int32_t i;
11910             std::memcpy(&i, &f, sizeof(f));
11911             return i;
11912         }
11913
11914         int64_t convert(double d) {
11915             static_assert(sizeof(double) == sizeof(int64_t),
11916                           "Important ULP matcher assumption violated");
11917             int64_t i;
11918             std::memcpy(&i, &d, sizeof(d));
11919             return i;
11920         }
11921
11922         template <typename FP> bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11923             // Comparison with NaN should always be false.
11924             // This way we can rule it out before getting into the ugly details
11925             if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11926                 return false;
11927             }
11928
11929             auto lc = convert(lhs);
11930             auto rc = convert(rhs);
11931
11932             if ((lc < 0) != (rc < 0)) {
11933                 // Potentially we can have +0 and -0
11934                 return lhs == rhs;
11935             }
11936
11937             // static cast as a workaround for IBM XLC
11938             auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11939             return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11940         }
11941
11942 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11943
11944         float nextafter(float x, float y) { return ::nextafterf(x, y); }
11945
11946         double nextafter(double x, double y) { return ::nextafter(x, y); }
11947
11948 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11949
11950         template <typename FP> FP step(FP start, FP direction, uint64_t steps) {
11951             for (uint64_t i = 0; i < steps; ++i) {
11952 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11953                 start = Catch::nextafter(start, direction);
11954 #else
11955                 start = std::nextafter(start, direction);
11956 #endif
11957             }
11958             return start;
11959         }
11960
11961         // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11962         // But without the subtraction to allow for INFINITY in comparison
11963         bool marginComparison(double lhs, double rhs, double margin) {
11964             return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11965         }
11966
11967         template <typename FloatingPoint> void write(std::ostream& out, FloatingPoint num) {
11968             out << std::scientific
11969                 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) << num;
11970         }
11971
11972     } // end anonymous namespace
11973
11974     namespace Matchers {
11975         namespace Floating {
11976
11977             enum class FloatingPointKind : uint8_t { Float, Double };
11978
11979             WithinAbsMatcher::WithinAbsMatcher(double target, double margin) :
11980                 m_target{target}, m_margin{margin} {
11981                 CATCH_ENFORCE(margin >= 0,
11982                               "Invalid margin: " << margin << '.'
11983                                                  << " Margin has to be non-negative.");
11984             }
11985
11986             // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11987             // But without the subtraction to allow for INFINITY in comparison
11988             bool WithinAbsMatcher::match(double const& matchee) const {
11989                 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11990             }
11991
11992             std::string WithinAbsMatcher::describe() const {
11993                 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " +
11994                        ::Catch::Detail::stringify(m_target);
11995             }
11996
11997             WithinUlpsMatcher::WithinUlpsMatcher(double target,
11998                                                  uint64_t ulps,
11999                                                  FloatingPointKind baseType) :
12000                 m_target{target}, m_ulps{ulps}, m_type{baseType} {
12001                 CATCH_ENFORCE(m_type == FloatingPointKind::Double ||
12002                                   m_ulps < (std::numeric_limits<uint32_t>::max)(),
12003                               "Provided ULP is impossibly large for a float comparison.");
12004             }
12005
12006 #if defined(__clang__)
12007 #pragma clang diagnostic push
12008 // Clang <3.5 reports on the default branch in the switch below
12009 #pragma clang diagnostic ignored "-Wunreachable-code"
12010 #endif
12011
12012             bool WithinUlpsMatcher::match(double const& matchee) const {
12013                 switch (m_type) {
12014                     case FloatingPointKind::Float:
12015                         return almostEqualUlps<float>(
12016                             static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
12017                     case FloatingPointKind::Double:
12018                         return almostEqualUlps<double>(matchee, m_target, m_ulps);
12019                     default:
12020                         CATCH_INTERNAL_ERROR("Unknown FloatingPointKind value");
12021                 }
12022             }
12023
12024 #if defined(__clang__)
12025 #pragma clang diagnostic pop
12026 #endif
12027
12028             std::string WithinUlpsMatcher::describe() const {
12029                 std::stringstream ret;
12030
12031                 ret << "is within " << m_ulps << " ULPs of ";
12032
12033                 if (m_type == FloatingPointKind::Float) {
12034                     write(ret, static_cast<float>(m_target));
12035                     ret << 'f';
12036                 } else {
12037                     write(ret, m_target);
12038                 }
12039
12040                 ret << " ([";
12041                 if (m_type == FloatingPointKind::Double) {
12042                     write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
12043                     ret << ", ";
12044                     write(ret, step(m_target, static_cast<double>(INFINITY), m_ulps));
12045                 } else {
12046                     // We have to cast INFINITY to float because of MinGW, see
12047                     // #1782
12048                     write(
12049                         ret,
12050                         step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
12051                     ret << ", ";
12052                     write(ret,
12053                           step(static_cast<float>(m_target), static_cast<float>(INFINITY), m_ulps));
12054                 }
12055                 ret << "])";
12056
12057                 return ret.str();
12058             }
12059
12060             WithinRelMatcher::WithinRelMatcher(double target, double epsilon) :
12061                 m_target(target), m_epsilon(epsilon) {
12062                 CATCH_ENFORCE(m_epsilon >= 0.,
12063                               "Relative comparison with epsilon <  0 does not "
12064                               "make sense.");
12065                 CATCH_ENFORCE(m_epsilon < 1.,
12066                               "Relative comparison with epsilon >= 1 does not "
12067                               "make sense.");
12068             }
12069
12070             bool WithinRelMatcher::match(double const& matchee) const {
12071                 const auto relMargin =
12072                     m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
12073                 return marginComparison(matchee, m_target, std::isinf(relMargin) ? 0 : relMargin);
12074             }
12075
12076             std::string WithinRelMatcher::describe() const {
12077                 Catch::ReusableStringStream sstr;
12078                 sstr << "and " << m_target << " are within " << m_epsilon * 100.
12079                      << "% of each other";
12080                 return sstr.str();
12081             }
12082
12083         } // namespace Floating
12084
12085         Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
12086             return Floating::WithinUlpsMatcher(
12087                 target, maxUlpDiff, Floating::FloatingPointKind::Double);
12088         }
12089
12090         Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
12091             return Floating::WithinUlpsMatcher(
12092                 target, maxUlpDiff, Floating::FloatingPointKind::Float);
12093         }
12094
12095         Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
12096             return Floating::WithinAbsMatcher(target, margin);
12097         }
12098
12099         Floating::WithinRelMatcher WithinRel(double target, double eps) {
12100             return Floating::WithinRelMatcher(target, eps);
12101         }
12102
12103         Floating::WithinRelMatcher WithinRel(double target) {
12104             return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
12105         }
12106
12107         Floating::WithinRelMatcher WithinRel(float target, float eps) {
12108             return Floating::WithinRelMatcher(target, eps);
12109         }
12110
12111         Floating::WithinRelMatcher WithinRel(float target) {
12112             return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
12113         }
12114
12115     } // namespace Matchers
12116 } // namespace Catch
12117 // end catch_matchers_floating.cpp
12118 // start catch_matchers_generic.cpp
12119
12120 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
12121     if (desc.empty()) {
12122         return "matches undescribed predicate";
12123     } else {
12124         return "matches predicate: \"" + desc + '"';
12125     }
12126 }
12127 // end catch_matchers_generic.cpp
12128 // start catch_matchers_string.cpp
12129
12130 #include <regex>
12131
12132 namespace Catch {
12133     namespace Matchers {
12134
12135         namespace StdString {
12136
12137             CasedString::CasedString(std::string const& str,
12138                                      CaseSensitive::Choice caseSensitivity) :
12139                 m_caseSensitivity(caseSensitivity), m_str(adjustString(str)) {}
12140             std::string CasedString::adjustString(std::string const& str) const {
12141                 return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str;
12142             }
12143             std::string CasedString::caseSensitivitySuffix() const {
12144                 return m_caseSensitivity == CaseSensitive::No ? " (case insensitive)"
12145                                                               : std::string();
12146             }
12147
12148             StringMatcherBase::StringMatcherBase(std::string const& operation,
12149                                                  CasedString const& comparator) :
12150                 m_comparator(comparator), m_operation(operation) {}
12151
12152             std::string StringMatcherBase::describe() const {
12153                 std::string description;
12154                 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
12155                                     m_comparator.caseSensitivitySuffix().size());
12156                 description += m_operation;
12157                 description += ": \"";
12158                 description += m_comparator.m_str;
12159                 description += "\"";
12160                 description += m_comparator.caseSensitivitySuffix();
12161                 return description;
12162             }
12163
12164             EqualsMatcher::EqualsMatcher(CasedString const& comparator) :
12165                 StringMatcherBase("equals", comparator) {}
12166
12167             bool EqualsMatcher::match(std::string const& source) const {
12168                 return m_comparator.adjustString(source) == m_comparator.m_str;
12169             }
12170
12171             ContainsMatcher::ContainsMatcher(CasedString const& comparator) :
12172                 StringMatcherBase("contains", comparator) {}
12173
12174             bool ContainsMatcher::match(std::string const& source) const {
12175                 return contains(m_comparator.adjustString(source), m_comparator.m_str);
12176             }
12177
12178             StartsWithMatcher::StartsWithMatcher(CasedString const& comparator) :
12179                 StringMatcherBase("starts with", comparator) {}
12180
12181             bool StartsWithMatcher::match(std::string const& source) const {
12182                 return startsWith(m_comparator.adjustString(source), m_comparator.m_str);
12183             }
12184
12185             EndsWithMatcher::EndsWithMatcher(CasedString const& comparator) :
12186                 StringMatcherBase("ends with", comparator) {}
12187
12188             bool EndsWithMatcher::match(std::string const& source) const {
12189                 return endsWith(m_comparator.adjustString(source), m_comparator.m_str);
12190             }
12191
12192             RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity) :
12193                 m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
12194
12195             bool RegexMatcher::match(std::string const& matchee) const {
12196                 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax
12197                                                      // option anyway
12198                 if (m_caseSensitivity == CaseSensitive::Choice::No) {
12199                     flags |= std::regex::icase;
12200                 }
12201                 auto reg = std::regex(m_regex, flags);
12202                 return std::regex_match(matchee, reg);
12203             }
12204
12205             std::string RegexMatcher::describe() const {
12206                 return "matches " + ::Catch::Detail::stringify(m_regex) +
12207                        ((m_caseSensitivity == CaseSensitive::Choice::Yes) ? " case sensitively"
12208                                                                           : " case insensitively");
12209             }
12210
12211         } // namespace StdString
12212
12213         StdString::EqualsMatcher Equals(std::string const& str,
12214                                         CaseSensitive::Choice caseSensitivity) {
12215             return StdString::EqualsMatcher(StdString::CasedString(str, caseSensitivity));
12216         }
12217         StdString::ContainsMatcher Contains(std::string const& str,
12218                                             CaseSensitive::Choice caseSensitivity) {
12219             return StdString::ContainsMatcher(StdString::CasedString(str, caseSensitivity));
12220         }
12221         StdString::EndsWithMatcher EndsWith(std::string const& str,
12222                                             CaseSensitive::Choice caseSensitivity) {
12223             return StdString::EndsWithMatcher(StdString::CasedString(str, caseSensitivity));
12224         }
12225         StdString::StartsWithMatcher StartsWith(std::string const& str,
12226                                                 CaseSensitive::Choice caseSensitivity) {
12227             return StdString::StartsWithMatcher(StdString::CasedString(str, caseSensitivity));
12228         }
12229
12230         StdString::RegexMatcher Matches(std::string const& regex,
12231                                         CaseSensitive::Choice caseSensitivity) {
12232             return StdString::RegexMatcher(regex, caseSensitivity);
12233         }
12234
12235     } // namespace Matchers
12236 } // namespace Catch
12237 // end catch_matchers_string.cpp
12238 // start catch_message.cpp
12239
12240 // start catch_uncaught_exceptions.h
12241
12242 namespace Catch {
12243     bool uncaught_exceptions();
12244 } // end namespace Catch
12245
12246 // end catch_uncaught_exceptions.h
12247 #include <cassert>
12248 #include <stack>
12249
12250 namespace Catch {
12251
12252     MessageInfo::MessageInfo(StringRef const& _macroName,
12253                              SourceLineInfo const& _lineInfo,
12254                              ResultWas::OfType _type) :
12255         macroName(_macroName), lineInfo(_lineInfo), type(_type), sequence(++globalCount) {}
12256
12257     bool MessageInfo::operator==(MessageInfo const& other) const {
12258         return sequence == other.sequence;
12259     }
12260
12261     bool MessageInfo::operator<(MessageInfo const& other) const {
12262         return sequence < other.sequence;
12263     }
12264
12265     // This may need protecting if threading support is added
12266     unsigned int MessageInfo::globalCount = 0;
12267
12268     ////////////////////////////////////////////////////////////////////////////
12269
12270     Catch::MessageBuilder::MessageBuilder(StringRef const& macroName,
12271                                           SourceLineInfo const& lineInfo,
12272                                           ResultWas::OfType type) :
12273         m_info(macroName, lineInfo, type) {}
12274
12275     ////////////////////////////////////////////////////////////////////////////
12276
12277     ScopedMessage::ScopedMessage(MessageBuilder const& builder) :
12278         m_info(builder.m_info), m_moved() {
12279         m_info.message = builder.m_stream.str();
12280         getResultCapture().pushScopedMessage(m_info);
12281     }
12282
12283     ScopedMessage::ScopedMessage(ScopedMessage&& old) : m_info(old.m_info), m_moved() {
12284         old.m_moved = true;
12285     }
12286
12287     ScopedMessage::~ScopedMessage() {
12288         if (!uncaught_exceptions() && !m_moved) {
12289             getResultCapture().popScopedMessage(m_info);
12290         }
12291     }
12292
12293     Capturer::Capturer(StringRef macroName,
12294                        SourceLineInfo const& lineInfo,
12295                        ResultWas::OfType resultType,
12296                        StringRef names) {
12297         auto trimmed = [&](size_t start, size_t end) {
12298             while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
12299                 ++start;
12300             }
12301             while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
12302                 --end;
12303             }
12304             return names.substr(start, end - start + 1);
12305         };
12306         auto skipq = [&](size_t start, char quote) {
12307             for (auto i = start + 1; i < names.size(); ++i) {
12308                 if (names[i] == quote)
12309                     return i;
12310                 if (names[i] == '\\')
12311                     ++i;
12312             }
12313             CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
12314         };
12315
12316         size_t start = 0;
12317         std::stack<char> openings;
12318         for (size_t pos = 0; pos < names.size(); ++pos) {
12319             char c = names[pos];
12320             switch (c) {
12321                 case '[':
12322                 case '{':
12323                 case '(':
12324                     // It is basically impossible to disambiguate between
12325                     // comparison and start of template args in this context
12326                     //            case '<':
12327                     openings.push(c);
12328                     break;
12329                 case ']':
12330                 case '}':
12331                 case ')':
12332                     //           case '>':
12333                     openings.pop();
12334                     break;
12335                 case '"':
12336                 case '\'':
12337                     pos = skipq(pos, c);
12338                     break;
12339                 case ',':
12340                     if (start != pos && openings.empty()) {
12341                         m_messages.emplace_back(macroName, lineInfo, resultType);
12342                         m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
12343                         m_messages.back().message += " := ";
12344                         start = pos;
12345                     }
12346             }
12347         }
12348         assert(openings.empty() && "Mismatched openings");
12349         m_messages.emplace_back(macroName, lineInfo, resultType);
12350         m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
12351         m_messages.back().message += " := ";
12352     }
12353     Capturer::~Capturer() {
12354         if (!uncaught_exceptions()) {
12355             assert(m_captured == m_messages.size());
12356             for (size_t i = 0; i < m_captured; ++i)
12357                 m_resultCapture.popScopedMessage(m_messages[i]);
12358         }
12359     }
12360
12361     void Capturer::captureValue(size_t index, std::string const& value) {
12362         assert(index < m_messages.size());
12363         m_messages[index].message += value;
12364         m_resultCapture.pushScopedMessage(m_messages[index]);
12365         m_captured++;
12366     }
12367
12368 } // end namespace Catch
12369 // end catch_message.cpp
12370 // start catch_output_redirect.cpp
12371
12372 // start catch_output_redirect.h
12373 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12374 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12375
12376 #include <cstdio>
12377 #include <iosfwd>
12378 #include <string>
12379
12380 namespace Catch {
12381
12382     class RedirectedStream {
12383         std::ostream& m_originalStream;
12384         std::ostream& m_redirectionStream;
12385         std::streambuf* m_prevBuf;
12386
12387     public:
12388         RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream);
12389         ~RedirectedStream();
12390     };
12391
12392     class RedirectedStdOut {
12393         ReusableStringStream m_rss;
12394         RedirectedStream m_cout;
12395
12396     public:
12397         RedirectedStdOut();
12398         auto str() const -> std::string;
12399     };
12400
12401     // StdErr has two constituent streams in C++, std::cerr and std::clog
12402     // This means that we need to redirect 2 streams into 1 to keep proper
12403     // order of writes
12404     class RedirectedStdErr {
12405         ReusableStringStream m_rss;
12406         RedirectedStream m_cerr;
12407         RedirectedStream m_clog;
12408
12409     public:
12410         RedirectedStdErr();
12411         auto str() const -> std::string;
12412     };
12413
12414     class RedirectedStreams {
12415     public:
12416         RedirectedStreams(RedirectedStreams const&) = delete;
12417         RedirectedStreams& operator=(RedirectedStreams const&) = delete;
12418         RedirectedStreams(RedirectedStreams&&) = delete;
12419         RedirectedStreams& operator=(RedirectedStreams&&) = delete;
12420
12421         RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
12422         ~RedirectedStreams();
12423
12424     private:
12425         std::string& m_redirectedCout;
12426         std::string& m_redirectedCerr;
12427         RedirectedStdOut m_redirectedStdOut;
12428         RedirectedStdErr m_redirectedStdErr;
12429     };
12430
12431 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12432
12433     // Windows's implementation of std::tmpfile is terrible (it tries
12434     // to create a file inside system folder, thus requiring elevated
12435     // privileges for the binary), so we have to use tmpnam(_s) and
12436     // create the file ourselves there.
12437     class TempFile {
12438     public:
12439         TempFile(TempFile const&) = delete;
12440         TempFile& operator=(TempFile const&) = delete;
12441         TempFile(TempFile&&) = delete;
12442         TempFile& operator=(TempFile&&) = delete;
12443
12444         TempFile();
12445         ~TempFile();
12446
12447         std::FILE* getFile();
12448         std::string getContents();
12449
12450     private:
12451         std::FILE* m_file = nullptr;
12452 #if defined(_MSC_VER)
12453         char m_buffer[L_tmpnam] = {0};
12454 #endif
12455     };
12456
12457     class OutputRedirect {
12458     public:
12459         OutputRedirect(OutputRedirect const&) = delete;
12460         OutputRedirect& operator=(OutputRedirect const&) = delete;
12461         OutputRedirect(OutputRedirect&&) = delete;
12462         OutputRedirect& operator=(OutputRedirect&&) = delete;
12463
12464         OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12465         ~OutputRedirect();
12466
12467     private:
12468         int m_originalStdout = -1;
12469         int m_originalStderr = -1;
12470         TempFile m_stdoutFile;
12471         TempFile m_stderrFile;
12472         std::string& m_stdoutDest;
12473         std::string& m_stderrDest;
12474     };
12475
12476 #endif
12477
12478 } // end namespace Catch
12479
12480 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12481 // end catch_output_redirect.h
12482 #include <cstdio>
12483 #include <cstring>
12484 #include <fstream>
12485 #include <sstream>
12486 #include <stdexcept>
12487
12488 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12489 #if defined(_MSC_VER)
12490 #include <io.h> //_dup and _dup2
12491 #define dup _dup
12492 #define dup2 _dup2
12493 #define fileno _fileno
12494 #else
12495 #include <unistd.h> // dup and dup2
12496 #endif
12497 #endif
12498
12499 namespace Catch {
12500
12501     RedirectedStream::RedirectedStream(std::ostream& originalStream,
12502                                        std::ostream& redirectionStream) :
12503         m_originalStream(originalStream),
12504         m_redirectionStream(redirectionStream),
12505         m_prevBuf(m_originalStream.rdbuf()) {
12506         m_originalStream.rdbuf(m_redirectionStream.rdbuf());
12507     }
12508
12509     RedirectedStream::~RedirectedStream() { m_originalStream.rdbuf(m_prevBuf); }
12510
12511     RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {}
12512     auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12513
12514     RedirectedStdErr::RedirectedStdErr() :
12515         m_cerr(Catch::cerr(), m_rss.get()), m_clog(Catch::clog(), m_rss.get()) {}
12516     auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12517
12518     RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr) :
12519         m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr) {}
12520
12521     RedirectedStreams::~RedirectedStreams() {
12522         m_redirectedCout += m_redirectedStdOut.str();
12523         m_redirectedCerr += m_redirectedStdErr.str();
12524     }
12525
12526 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12527
12528 #if defined(_MSC_VER)
12529     TempFile::TempFile() {
12530         if (tmpnam_s(m_buffer)) {
12531             CATCH_RUNTIME_ERROR("Could not get a temp filename");
12532         }
12533         if (fopen_s(&m_file, m_buffer, "w+")) {
12534             char buffer[100];
12535             if (strerror_s(buffer, errno)) {
12536                 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12537             }
12538             CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer
12539                                                                   << "' because: " << buffer);
12540         }
12541     }
12542 #else
12543     TempFile::TempFile() {
12544         m_file = std::tmpfile();
12545         if (!m_file) {
12546             CATCH_RUNTIME_ERROR("Could not create a temp file.");
12547         }
12548     }
12549
12550 #endif
12551
12552     TempFile::~TempFile() {
12553         // TBD: What to do about errors here?
12554         std::fclose(m_file);
12555         // We manually create the file on Windows only, on Linux
12556         // it will be autodeleted
12557 #if defined(_MSC_VER)
12558         std::remove(m_buffer);
12559 #endif
12560     }
12561
12562     FILE* TempFile::getFile() { return m_file; }
12563
12564     std::string TempFile::getContents() {
12565         std::stringstream sstr;
12566         char buffer[100] = {};
12567         std::rewind(m_file);
12568         while (std::fgets(buffer, sizeof(buffer), m_file)) {
12569             sstr << buffer;
12570         }
12571         return sstr.str();
12572     }
12573
12574     OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12575         m_originalStdout(dup(1)),
12576         m_originalStderr(dup(2)),
12577         m_stdoutDest(stdout_dest),
12578         m_stderrDest(stderr_dest) {
12579         dup2(fileno(m_stdoutFile.getFile()), 1);
12580         dup2(fileno(m_stderrFile.getFile()), 2);
12581     }
12582
12583     OutputRedirect::~OutputRedirect() {
12584         Catch::cout() << std::flush;
12585         fflush(stdout);
12586         // Since we support overriding these streams, we flush cerr
12587         // even though std::cerr is unbuffered
12588         Catch::cerr() << std::flush;
12589         Catch::clog() << std::flush;
12590         fflush(stderr);
12591
12592         dup2(m_originalStdout, 1);
12593         dup2(m_originalStderr, 2);
12594
12595         m_stdoutDest += m_stdoutFile.getContents();
12596         m_stderrDest += m_stderrFile.getContents();
12597     }
12598
12599 #endif // CATCH_CONFIG_NEW_CAPTURE
12600
12601 } // namespace Catch
12602
12603 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12604 #if defined(_MSC_VER)
12605 #undef dup
12606 #undef dup2
12607 #undef fileno
12608 #endif
12609 #endif
12610 // end catch_output_redirect.cpp
12611 // start catch_polyfills.cpp
12612
12613 #include <cmath>
12614
12615 namespace Catch {
12616
12617 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12618     bool isnan(float f) { return std::isnan(f); }
12619     bool isnan(double d) { return std::isnan(d); }
12620 #else
12621     // For now we only use this for embarcadero
12622     bool isnan(float f) { return std::_isnan(f); }
12623     bool isnan(double d) { return std::_isnan(d); }
12624 #endif
12625
12626 } // end namespace Catch
12627 // end catch_polyfills.cpp
12628 // start catch_random_number_generator.cpp
12629
12630 namespace Catch {
12631
12632     namespace {
12633
12634 #if defined(_MSC_VER)
12635 #pragma warning(push)
12636 #pragma warning(disable : 4146) // we negate uint32 during the rotate
12637 #endif
12638         // Safe rotr implementation thanks to John Regehr
12639         uint32_t rotate_right(uint32_t val, uint32_t count) {
12640             const uint32_t mask = 31;
12641             count &= mask;
12642             return (val >> count) | (val << (-count & mask));
12643         }
12644
12645 #if defined(_MSC_VER)
12646 #pragma warning(pop)
12647 #endif
12648
12649     } // namespace
12650
12651     SimplePcg32::SimplePcg32(result_type seed_) { seed(seed_); }
12652
12653     void SimplePcg32::seed(result_type seed_) {
12654         m_state = 0;
12655         (*this)();
12656         m_state += seed_;
12657         (*this)();
12658     }
12659
12660     void SimplePcg32::discard(uint64_t skip) {
12661         // We could implement this to run in O(log n) steps, but this
12662         // should suffice for our use case.
12663         for (uint64_t s = 0; s < skip; ++s) {
12664             static_cast<void>((*this)());
12665         }
12666     }
12667
12668     SimplePcg32::result_type SimplePcg32::operator()() {
12669         // prepare the output value
12670         const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12671         const auto output = rotate_right(xorshifted, m_state >> 59u);
12672
12673         // advance state
12674         m_state = m_state * 6364136223846793005ULL + s_inc;
12675
12676         return output;
12677     }
12678
12679     bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12680         return lhs.m_state == rhs.m_state;
12681     }
12682
12683     bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12684         return lhs.m_state != rhs.m_state;
12685     }
12686 } // namespace Catch
12687 // end catch_random_number_generator.cpp
12688 // start catch_registry_hub.cpp
12689
12690 // start catch_test_case_registry_impl.h
12691
12692 #include <vector>
12693 #include <set>
12694 #include <algorithm>
12695 #include <ios>
12696
12697 namespace Catch {
12698
12699     class TestCase;
12700     struct IConfig;
12701
12702     std::vector<TestCase> sortTests(IConfig const& config,
12703                                     std::vector<TestCase> const& unsortedTestCases);
12704
12705     bool isThrowSafe(TestCase const& testCase, IConfig const& config);
12706     bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config);
12707
12708     void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions);
12709
12710     std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
12711                                       TestSpec const& testSpec,
12712                                       IConfig const& config);
12713     std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config);
12714
12715     class TestRegistry : public ITestCaseRegistry {
12716     public:
12717         virtual ~TestRegistry() = default;
12718
12719         virtual void registerTest(TestCase const& testCase);
12720
12721         std::vector<TestCase> const& getAllTests() const override;
12722         std::vector<TestCase> const& getAllTestsSorted(IConfig const& config) const override;
12723
12724     private:
12725         std::vector<TestCase> m_functions;
12726         mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12727         mutable std::vector<TestCase> m_sortedFunctions;
12728         std::size_t m_unnamedCount = 0;
12729         std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12730     };
12731
12732     ///////////////////////////////////////////////////////////////////////////
12733
12734     class TestInvokerAsFunction : public ITestInvoker {
12735         void (*m_testAsFunction)();
12736
12737     public:
12738         TestInvokerAsFunction(void (*testAsFunction)()) noexcept;
12739
12740         void invoke() const override;
12741     };
12742
12743     std::string extractClassName(StringRef const& classOrQualifiedMethodName);
12744
12745     ///////////////////////////////////////////////////////////////////////////
12746
12747 } // end namespace Catch
12748
12749 // end catch_test_case_registry_impl.h
12750 // start catch_reporter_registry.h
12751
12752 #include <map>
12753
12754 namespace Catch {
12755
12756     class ReporterRegistry : public IReporterRegistry {
12757
12758     public:
12759         ~ReporterRegistry() override;
12760
12761         IStreamingReporterPtr create(std::string const& name,
12762                                      IConfigPtr const& config) const override;
12763
12764         void registerReporter(std::string const& name, IReporterFactoryPtr const& factory);
12765         void registerListener(IReporterFactoryPtr const& factory);
12766
12767         FactoryMap const& getFactories() const override;
12768         Listeners const& getListeners() const override;
12769
12770     private:
12771         FactoryMap m_factories;
12772         Listeners m_listeners;
12773     };
12774 } // namespace Catch
12775
12776 // end catch_reporter_registry.h
12777 // start catch_tag_alias_registry.h
12778
12779 // start catch_tag_alias.h
12780
12781 #include <string>
12782
12783 namespace Catch {
12784
12785     struct TagAlias {
12786         TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12787
12788         std::string tag;
12789         SourceLineInfo lineInfo;
12790     };
12791
12792 } // end namespace Catch
12793
12794 // end catch_tag_alias.h
12795 #include <map>
12796
12797 namespace Catch {
12798
12799     class TagAliasRegistry : public ITagAliasRegistry {
12800     public:
12801         ~TagAliasRegistry() override;
12802         TagAlias const* find(std::string const& alias) const override;
12803         std::string expandAliases(std::string const& unexpandedTestSpec) const override;
12804         void add(std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo);
12805
12806     private:
12807         std::map<std::string, TagAlias> m_registry;
12808     };
12809
12810 } // end namespace Catch
12811
12812 // end catch_tag_alias_registry.h
12813 // start catch_startup_exception_registry.h
12814
12815 #include <vector>
12816 #include <exception>
12817
12818 namespace Catch {
12819
12820     class StartupExceptionRegistry {
12821 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12822     public:
12823         void add(std::exception_ptr const& exception) noexcept;
12824         std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12825
12826     private:
12827         std::vector<std::exception_ptr> m_exceptions;
12828 #endif
12829     };
12830
12831 } // end namespace Catch
12832
12833 // end catch_startup_exception_registry.h
12834 // start catch_singletons.hpp
12835
12836 namespace Catch {
12837
12838     struct ISingleton {
12839         virtual ~ISingleton();
12840     };
12841
12842     void addSingleton(ISingleton* singleton);
12843     void cleanupSingletons();
12844
12845     template <typename SingletonImplT,
12846               typename InterfaceT = SingletonImplT,
12847               typename MutableInterfaceT = InterfaceT>
12848     class Singleton : SingletonImplT, public ISingleton {
12849
12850         static auto getInternal() -> Singleton* {
12851             static Singleton* s_instance = nullptr;
12852             if (!s_instance) {
12853                 s_instance = new Singleton;
12854                 addSingleton(s_instance);
12855             }
12856             return s_instance;
12857         }
12858
12859     public:
12860         static auto get() -> InterfaceT const& { return *getInternal(); }
12861         static auto getMutable() -> MutableInterfaceT& { return *getInternal(); }
12862     };
12863
12864 } // namespace Catch
12865
12866 // end catch_singletons.hpp
12867 namespace Catch {
12868
12869     namespace {
12870
12871         class RegistryHub : public IRegistryHub, public IMutableRegistryHub, private NonCopyable {
12872
12873         public: // IRegistryHub
12874             RegistryHub() = default;
12875             IReporterRegistry const& getReporterRegistry() const override {
12876                 return m_reporterRegistry;
12877             }
12878             ITestCaseRegistry const& getTestCaseRegistry() const override {
12879                 return m_testCaseRegistry;
12880             }
12881             IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12882                 return m_exceptionTranslatorRegistry;
12883             }
12884             ITagAliasRegistry const& getTagAliasRegistry() const override {
12885                 return m_tagAliasRegistry;
12886             }
12887             StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12888                 return m_exceptionRegistry;
12889             }
12890
12891         public: // IMutableRegistryHub
12892             void registerReporter(std::string const& name,
12893                                   IReporterFactoryPtr const& factory) override {
12894                 m_reporterRegistry.registerReporter(name, factory);
12895             }
12896             void registerListener(IReporterFactoryPtr const& factory) override {
12897                 m_reporterRegistry.registerListener(factory);
12898             }
12899             void registerTest(TestCase const& testInfo) override {
12900                 m_testCaseRegistry.registerTest(testInfo);
12901             }
12902             void registerTranslator(const IExceptionTranslator* translator) override {
12903                 m_exceptionTranslatorRegistry.registerTranslator(translator);
12904             }
12905             void registerTagAlias(std::string const& alias,
12906                                   std::string const& tag,
12907                                   SourceLineInfo const& lineInfo) override {
12908                 m_tagAliasRegistry.add(alias, tag, lineInfo);
12909             }
12910             void registerStartupException() noexcept override {
12911 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12912                 m_exceptionRegistry.add(std::current_exception());
12913 #else
12914                 CATCH_INTERNAL_ERROR("Attempted to register active exception "
12915                                      "under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12916 #endif
12917             }
12918             IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12919                 return m_enumValuesRegistry;
12920             }
12921
12922         private:
12923             TestRegistry m_testCaseRegistry;
12924             ReporterRegistry m_reporterRegistry;
12925             ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12926             TagAliasRegistry m_tagAliasRegistry;
12927             StartupExceptionRegistry m_exceptionRegistry;
12928             Detail::EnumValuesRegistry m_enumValuesRegistry;
12929         };
12930     } // namespace
12931
12932     using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12933
12934     IRegistryHub const& getRegistryHub() { return RegistryHubSingleton::get(); }
12935     IMutableRegistryHub& getMutableRegistryHub() { return RegistryHubSingleton::getMutable(); }
12936     void cleanUp() {
12937         cleanupSingletons();
12938         cleanUpContext();
12939     }
12940     std::string translateActiveException() {
12941         return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12942     }
12943
12944 } // end namespace Catch
12945 // end catch_registry_hub.cpp
12946 // start catch_reporter_registry.cpp
12947
12948 namespace Catch {
12949
12950     ReporterRegistry::~ReporterRegistry() = default;
12951
12952     IStreamingReporterPtr ReporterRegistry::create(std::string const& name,
12953                                                    IConfigPtr const& config) const {
12954         auto it = m_factories.find(name);
12955         if (it == m_factories.end())
12956             return nullptr;
12957         return it->second->create(ReporterConfig(config));
12958     }
12959
12960     void ReporterRegistry::registerReporter(std::string const& name,
12961                                             IReporterFactoryPtr const& factory) {
12962         m_factories.emplace(name, factory);
12963     }
12964     void ReporterRegistry::registerListener(IReporterFactoryPtr const& factory) {
12965         m_listeners.push_back(factory);
12966     }
12967
12968     IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12969         return m_factories;
12970     }
12971     IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12972         return m_listeners;
12973     }
12974
12975 } // namespace Catch
12976 // end catch_reporter_registry.cpp
12977 // start catch_result_type.cpp
12978
12979 namespace Catch {
12980
12981     bool isOk(ResultWas::OfType resultType) { return (resultType & ResultWas::FailureBit) == 0; }
12982     bool isJustInfo(int flags) { return flags == ResultWas::Info; }
12983
12984     ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs) {
12985         return static_cast<ResultDisposition::Flags>(static_cast<int>(lhs) | static_cast<int>(rhs));
12986     }
12987
12988     bool shouldContinueOnFailure(int flags) {
12989         return (flags & ResultDisposition::ContinueOnFailure) != 0;
12990     }
12991     bool shouldSuppressFailure(int flags) { return (flags & ResultDisposition::SuppressFail) != 0; }
12992
12993 } // end namespace Catch
12994 // end catch_result_type.cpp
12995 // start catch_run_context.cpp
12996
12997 #include <cassert>
12998 #include <algorithm>
12999 #include <sstream>
13000
13001 namespace Catch {
13002
13003     namespace Generators {
13004         struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
13005             GeneratorBasePtr m_generator;
13006
13007             GeneratorTracker(TestCaseTracking::NameAndLocation const& nameAndLocation,
13008                              TrackerContext& ctx,
13009                              ITracker* parent) :
13010                 TrackerBase(nameAndLocation, ctx, parent) {}
13011             ~GeneratorTracker();
13012
13013             static GeneratorTracker&
13014             acquire(TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation) {
13015                 std::shared_ptr<GeneratorTracker> tracker;
13016
13017                 ITracker& currentTracker = ctx.currentTracker();
13018                 // Under specific circumstances, the generator we want
13019                 // to acquire is also the current tracker. If this is
13020                 // the case, we have to avoid looking through current
13021                 // tracker's children, and instead return the current
13022                 // tracker.
13023                 // A case where this check is important is e.g.
13024                 //     for (int i = 0; i < 5; ++i) {
13025                 //         int n = GENERATE(1, 2);
13026                 //     }
13027                 //
13028                 // without it, the code above creates 5 nested generators.
13029                 if (currentTracker.nameAndLocation() == nameAndLocation) {
13030                     auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
13031                     assert(thisTracker);
13032                     assert(thisTracker->isGeneratorTracker());
13033                     tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
13034                 } else if (TestCaseTracking::ITrackerPtr childTracker =
13035                                currentTracker.findChild(nameAndLocation)) {
13036                     assert(childTracker);
13037                     assert(childTracker->isGeneratorTracker());
13038                     tracker = std::static_pointer_cast<GeneratorTracker>(childTracker);
13039                 } else {
13040                     tracker =
13041                         std::make_shared<GeneratorTracker>(nameAndLocation, ctx, &currentTracker);
13042                     currentTracker.addChild(tracker);
13043                 }
13044
13045                 if (!tracker->isComplete()) {
13046                     tracker->open();
13047                 }
13048
13049                 return *tracker;
13050             }
13051
13052             // TrackerBase interface
13053             bool isGeneratorTracker() const override { return true; }
13054             auto hasGenerator() const -> bool override { return !!m_generator; }
13055             void close() override {
13056                 TrackerBase::close();
13057                 // If a generator has a child (it is followed by a section)
13058                 // and none of its children have started, then we must wait
13059                 // until later to start consuming its values.
13060                 // This catches cases where `GENERATE` is placed between two
13061                 // `SECTION`s.
13062                 // **The check for m_children.empty cannot be removed**.
13063                 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
13064                 const bool should_wait_for_child = [&]() {
13065                     // No children -> nobody to wait for
13066                     if (m_children.empty()) {
13067                         return false;
13068                     }
13069                     // If at least one child started executing, don't wait
13070                     if (std::find_if(m_children.begin(),
13071                                      m_children.end(),
13072                                      [](TestCaseTracking::ITrackerPtr tracker) {
13073                                          return tracker->hasStarted();
13074                                      }) != m_children.end())
13075                     {
13076                         return false;
13077                     }
13078
13079                     // No children have started. We need to check if they _can_
13080                     // start, and thus we should wait for them, or they cannot
13081                     // start (due to filters), and we shouldn't wait for them
13082                     auto* parent = m_parent;
13083                     // This is safe: there is always at least one section
13084                     // tracker in a test case tracking tree
13085                     while (!parent->isSectionTracker()) {
13086                         parent = &(parent->parent());
13087                     }
13088                     assert(parent && "Missing root (test case) level section");
13089
13090                     auto const& parentSection = static_cast<SectionTracker&>(*parent);
13091                     auto const& filters = parentSection.getFilters();
13092                     // No filters -> no restrictions on running sections
13093                     if (filters.empty()) {
13094                         return true;
13095                     }
13096
13097                     for (auto const& child : m_children) {
13098                         if (child->isSectionTracker() &&
13099                             std::find(filters.begin(),
13100                                       filters.end(),
13101                                       static_cast<SectionTracker&>(*child).trimmedName()) !=
13102                                 filters.end())
13103                         {
13104                             return true;
13105                         }
13106                     }
13107                     return false;
13108                 }();
13109
13110                 // This check is a bit tricky, because m_generator->next()
13111                 // has a side-effect, where it consumes generator's current
13112                 // value, but we do not want to invoke the side-effect if
13113                 // this generator is still waiting for any child to start.
13114                 if (should_wait_for_child ||
13115                     (m_runState == CompletedSuccessfully && m_generator->next())) {
13116                     m_children.clear();
13117                     m_runState = Executing;
13118                 }
13119             }
13120
13121             // IGeneratorTracker interface
13122             auto getGenerator() const -> GeneratorBasePtr const& override { return m_generator; }
13123             void setGenerator(GeneratorBasePtr&& generator) override {
13124                 m_generator = std::move(generator);
13125             }
13126         };
13127         GeneratorTracker::~GeneratorTracker() {}
13128     } // namespace Generators
13129
13130     RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter) :
13131         m_runInfo(_config->name()),
13132         m_context(getCurrentMutableContext()),
13133         m_config(_config),
13134         m_reporter(std::move(reporter)),
13135         m_lastAssertionInfo{
13136             StringRef(), SourceLineInfo("", 0), StringRef(), ResultDisposition::Normal},
13137         m_includeSuccessfulResults(m_config->includeSuccessfulResults() ||
13138                                    m_reporter->getPreferences().shouldReportAllAssertions) {
13139         m_context.setRunner(this);
13140         m_context.setConfig(m_config);
13141         m_context.setResultCapture(this);
13142         m_reporter->testRunStarting(m_runInfo);
13143     }
13144
13145     RunContext::~RunContext() {
13146         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
13147     }
13148
13149     void RunContext::testGroupStarting(std::string const& testSpec,
13150                                        std::size_t groupIndex,
13151                                        std::size_t groupsCount) {
13152         m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
13153     }
13154
13155     void RunContext::testGroupEnded(std::string const& testSpec,
13156                                     Totals const& totals,
13157                                     std::size_t groupIndex,
13158                                     std::size_t groupsCount) {
13159         m_reporter->testGroupEnded(
13160             TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
13161     }
13162
13163     Totals RunContext::runTest(TestCase const& testCase) {
13164         Totals prevTotals = m_totals;
13165
13166         std::string redirectedCout;
13167         std::string redirectedCerr;
13168
13169         auto const& testInfo = testCase.getTestCaseInfo();
13170
13171         m_reporter->testCaseStarting(testInfo);
13172
13173         m_activeTestCase = &testCase;
13174
13175         ITracker& rootTracker = m_trackerContext.startRun();
13176         assert(rootTracker.isSectionTracker());
13177         static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
13178         do {
13179             m_trackerContext.startCycle();
13180             m_testCaseTracker = &SectionTracker::acquire(
13181                 m_trackerContext,
13182                 TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
13183             runCurrentTest(redirectedCout, redirectedCerr);
13184         } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
13185
13186         Totals deltaTotals = m_totals.delta(prevTotals);
13187         if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
13188             deltaTotals.assertions.failed++;
13189             deltaTotals.testCases.passed--;
13190             deltaTotals.testCases.failed++;
13191         }
13192         m_totals.testCases += deltaTotals.testCases;
13193         m_reporter->testCaseEnded(
13194             TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting()));
13195
13196         m_activeTestCase = nullptr;
13197         m_testCaseTracker = nullptr;
13198
13199         return deltaTotals;
13200     }
13201
13202     IConfigPtr RunContext::config() const { return m_config; }
13203
13204     IStreamingReporter& RunContext::reporter() const { return *m_reporter; }
13205
13206     void RunContext::assertionEnded(AssertionResult const& result) {
13207         if (result.getResultType() == ResultWas::Ok) {
13208             m_totals.assertions.passed++;
13209             m_lastAssertionPassed = true;
13210         } else if (!result.isOk()) {
13211             m_lastAssertionPassed = false;
13212             if (m_activeTestCase->getTestCaseInfo().okToFail())
13213                 m_totals.assertions.failedButOk++;
13214             else
13215                 m_totals.assertions.failed++;
13216         } else {
13217             m_lastAssertionPassed = true;
13218         }
13219
13220         // We have no use for the return value (whether messages should be
13221         // cleared), because messages were made scoped and should be let to
13222         // clear themselves out.
13223         static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
13224
13225         if (result.getResultType() != ResultWas::Warning)
13226             m_messageScopes.clear();
13227
13228         // Reset working state
13229         resetAssertionInfo();
13230         m_lastResult = result;
13231     }
13232     void RunContext::resetAssertionInfo() {
13233         m_lastAssertionInfo.macroName = StringRef();
13234         m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
13235     }
13236
13237     bool RunContext::sectionStarted(SectionInfo const& sectionInfo, Counts& assertions) {
13238         ITracker& sectionTracker = SectionTracker::acquire(
13239             m_trackerContext,
13240             TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
13241         if (!sectionTracker.isOpen())
13242             return false;
13243         m_activeSections.push_back(&sectionTracker);
13244
13245         m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
13246
13247         m_reporter->sectionStarting(sectionInfo);
13248
13249         assertions = m_totals.assertions;
13250
13251         return true;
13252     }
13253     auto RunContext::acquireGeneratorTracker(StringRef generatorName,
13254                                              SourceLineInfo const& lineInfo) -> IGeneratorTracker& {
13255         using namespace Generators;
13256         GeneratorTracker& tracker = GeneratorTracker::acquire(
13257             m_trackerContext,
13258             TestCaseTracking::NameAndLocation(static_cast<std::string>(generatorName), lineInfo));
13259         m_lastAssertionInfo.lineInfo = lineInfo;
13260         return tracker;
13261     }
13262
13263     bool RunContext::testForMissingAssertions(Counts& assertions) {
13264         if (assertions.total() != 0)
13265             return false;
13266         if (!m_config->warnAboutMissingAssertions())
13267             return false;
13268         if (m_trackerContext.currentTracker().hasChildren())
13269             return false;
13270         m_totals.assertions.failed++;
13271         assertions.failed++;
13272         return true;
13273     }
13274
13275     void RunContext::sectionEnded(SectionEndInfo const& endInfo) {
13276         Counts assertions = m_totals.assertions - endInfo.prevAssertions;
13277         bool missingAssertions = testForMissingAssertions(assertions);
13278
13279         if (!m_activeSections.empty()) {
13280             m_activeSections.back()->close();
13281             m_activeSections.pop_back();
13282         }
13283
13284         m_reporter->sectionEnded(SectionStats(
13285             endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
13286         m_messages.clear();
13287         m_messageScopes.clear();
13288     }
13289
13290     void RunContext::sectionEndedEarly(SectionEndInfo const& endInfo) {
13291         if (m_unfinishedSections.empty())
13292             m_activeSections.back()->fail();
13293         else
13294             m_activeSections.back()->close();
13295         m_activeSections.pop_back();
13296
13297         m_unfinishedSections.push_back(endInfo);
13298     }
13299
13300 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
13301     void RunContext::benchmarkPreparing(std::string const& name) {
13302         m_reporter->benchmarkPreparing(name);
13303     }
13304     void RunContext::benchmarkStarting(BenchmarkInfo const& info) {
13305         m_reporter->benchmarkStarting(info);
13306     }
13307     void RunContext::benchmarkEnded(BenchmarkStats<> const& stats) {
13308         m_reporter->benchmarkEnded(stats);
13309     }
13310     void RunContext::benchmarkFailed(std::string const& error) {
13311         m_reporter->benchmarkFailed(error);
13312     }
13313 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
13314
13315     void RunContext::pushScopedMessage(MessageInfo const& message) {
13316         m_messages.push_back(message);
13317     }
13318
13319     void RunContext::popScopedMessage(MessageInfo const& message) {
13320         m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message),
13321                          m_messages.end());
13322     }
13323
13324     void RunContext::emplaceUnscopedMessage(MessageBuilder const& builder) {
13325         m_messageScopes.emplace_back(builder);
13326     }
13327
13328     std::string RunContext::getCurrentTestName() const {
13329         return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string();
13330     }
13331
13332     const AssertionResult* RunContext::getLastResult() const { return &(*m_lastResult); }
13333
13334     void RunContext::exceptionEarlyReported() { m_shouldReportUnexpected = false; }
13335
13336     void RunContext::handleFatalErrorCondition(StringRef message) {
13337         // First notify reporter that bad things happened
13338         m_reporter->fatalErrorEncountered(message);
13339
13340         // Don't rebuild the result -- the stringification itself can cause more
13341         // fatal errors Instead, fake a result data.
13342         AssertionResultData tempResult(ResultWas::FatalErrorCondition, {false});
13343         tempResult.message = static_cast<std::string>(message);
13344         AssertionResult result(m_lastAssertionInfo, tempResult);
13345
13346         assertionEnded(result);
13347
13348         handleUnfinishedSections();
13349
13350         // Recreate section for test case (as we will lose the one that was in
13351         // scope)
13352         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13353         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13354
13355         Counts assertions;
13356         assertions.failed = 1;
13357         SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
13358         m_reporter->sectionEnded(testCaseSectionStats);
13359
13360         auto const& testInfo = m_activeTestCase->getTestCaseInfo();
13361
13362         Totals deltaTotals;
13363         deltaTotals.testCases.failed = 1;
13364         deltaTotals.assertions.failed = 1;
13365         m_reporter->testCaseEnded(
13366             TestCaseStats(testInfo, deltaTotals, std::string(), std::string(), false));
13367         m_totals.testCases.failed++;
13368         testGroupEnded(std::string(), m_totals, 1, 1);
13369         m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
13370     }
13371
13372     bool RunContext::lastAssertionPassed() { return m_lastAssertionPassed; }
13373
13374     void RunContext::assertionPassed() {
13375         m_lastAssertionPassed = true;
13376         ++m_totals.assertions.passed;
13377         resetAssertionInfo();
13378         m_messageScopes.clear();
13379     }
13380
13381     bool RunContext::aborting() const {
13382         return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
13383     }
13384
13385     void RunContext::runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr) {
13386         auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13387         SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13388         m_reporter->sectionStarting(testCaseSection);
13389         Counts prevAssertions = m_totals.assertions;
13390         double duration = 0;
13391         m_shouldReportUnexpected = true;
13392         m_lastAssertionInfo = {
13393             "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal};
13394
13395         seedRng(*m_config);
13396
13397         Timer timer;
13398         CATCH_TRY {
13399             if (m_reporter->getPreferences().shouldRedirectStdOut) {
13400 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
13401                 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
13402
13403                 timer.start();
13404                 invokeActiveTestCase();
13405 #else
13406                 OutputRedirect r(redirectedCout, redirectedCerr);
13407                 timer.start();
13408                 invokeActiveTestCase();
13409 #endif
13410             } else {
13411                 timer.start();
13412                 invokeActiveTestCase();
13413             }
13414             duration = timer.getElapsedSeconds();
13415         }
13416         CATCH_CATCH_ANON(TestFailureException&) {
13417             // This just means the test was aborted due to failure
13418         }
13419         CATCH_CATCH_ALL {
13420             // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under
13421             // REQUIRE assertions are reported without translation at the point
13422             // of origin.
13423             if (m_shouldReportUnexpected) {
13424                 AssertionReaction dummyReaction;
13425                 handleUnexpectedInflightException(
13426                     m_lastAssertionInfo, translateActiveException(), dummyReaction);
13427             }
13428         }
13429         Counts assertions = m_totals.assertions - prevAssertions;
13430         bool missingAssertions = testForMissingAssertions(assertions);
13431
13432         m_testCaseTracker->close();
13433         handleUnfinishedSections();
13434         m_messages.clear();
13435         m_messageScopes.clear();
13436
13437         SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13438         m_reporter->sectionEnded(testCaseSectionStats);
13439     }
13440
13441     void RunContext::invokeActiveTestCase() {
13442         FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13443         m_activeTestCase->invoke();
13444     }
13445
13446     void RunContext::handleUnfinishedSections() {
13447         // If sections ended prematurely due to an exception we stored their
13448         // infos here so we can tear them down outside the unwind process.
13449         for (auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend();
13450              it != itEnd;
13451              ++it)
13452             sectionEnded(*it);
13453         m_unfinishedSections.clear();
13454     }
13455
13456     void RunContext::handleExpr(AssertionInfo const& info,
13457                                 ITransientExpression const& expr,
13458                                 AssertionReaction& reaction) {
13459         m_reporter->assertionStarting(info);
13460
13461         bool negated = isFalseTest(info.resultDisposition);
13462         bool result = expr.getResult() != negated;
13463
13464         if (result) {
13465             if (!m_includeSuccessfulResults) {
13466                 assertionPassed();
13467             } else {
13468                 reportExpr(info, ResultWas::Ok, &expr, negated);
13469             }
13470         } else {
13471             reportExpr(info, ResultWas::ExpressionFailed, &expr, negated);
13472             populateReaction(reaction);
13473         }
13474     }
13475     void RunContext::reportExpr(AssertionInfo const& info,
13476                                 ResultWas::OfType resultType,
13477                                 ITransientExpression const* expr,
13478                                 bool negated) {
13479
13480         m_lastAssertionInfo = info;
13481         AssertionResultData data(resultType, LazyExpression(negated));
13482
13483         AssertionResult assertionResult{info, data};
13484         assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13485
13486         assertionEnded(assertionResult);
13487     }
13488
13489     void RunContext::handleMessage(AssertionInfo const& info,
13490                                    ResultWas::OfType resultType,
13491                                    StringRef const& message,
13492                                    AssertionReaction& reaction) {
13493         m_reporter->assertionStarting(info);
13494
13495         m_lastAssertionInfo = info;
13496
13497         AssertionResultData data(resultType, LazyExpression(false));
13498         data.message = static_cast<std::string>(message);
13499         AssertionResult assertionResult{m_lastAssertionInfo, data};
13500         assertionEnded(assertionResult);
13501         if (!assertionResult.isOk())
13502             populateReaction(reaction);
13503     }
13504     void RunContext::handleUnexpectedExceptionNotThrown(AssertionInfo const& info,
13505                                                         AssertionReaction& reaction) {
13506         handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13507     }
13508
13509     void RunContext::handleUnexpectedInflightException(AssertionInfo const& info,
13510                                                        std::string const& message,
13511                                                        AssertionReaction& reaction) {
13512         m_lastAssertionInfo = info;
13513
13514         AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13515         data.message = message;
13516         AssertionResult assertionResult{info, data};
13517         assertionEnded(assertionResult);
13518         populateReaction(reaction);
13519     }
13520
13521     void RunContext::populateReaction(AssertionReaction& reaction) {
13522         reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13523         reaction.shouldThrow =
13524             aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13525     }
13526
13527     void RunContext::handleIncomplete(AssertionInfo const& info) {
13528         m_lastAssertionInfo = info;
13529
13530         AssertionResultData data(ResultWas::ThrewException, LazyExpression(false));
13531         data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13532         AssertionResult assertionResult{info, data};
13533         assertionEnded(assertionResult);
13534     }
13535     void RunContext::handleNonExpr(AssertionInfo const& info,
13536                                    ResultWas::OfType resultType,
13537                                    AssertionReaction& reaction) {
13538         m_lastAssertionInfo = info;
13539
13540         AssertionResultData data(resultType, LazyExpression(false));
13541         AssertionResult assertionResult{info, data};
13542         assertionEnded(assertionResult);
13543
13544         if (!assertionResult.isOk())
13545             populateReaction(reaction);
13546     }
13547
13548     IResultCapture& getResultCapture() {
13549         if (auto* capture = getCurrentContext().getResultCapture())
13550             return *capture;
13551         else
13552             CATCH_INTERNAL_ERROR("No result capture instance");
13553     }
13554
13555     void seedRng(IConfig const& config) {
13556         if (config.rngSeed() != 0) {
13557             std::srand(config.rngSeed());
13558             rng().seed(config.rngSeed());
13559         }
13560     }
13561
13562     unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); }
13563
13564 } // namespace Catch
13565 // end catch_run_context.cpp
13566 // start catch_section.cpp
13567
13568 namespace Catch {
13569
13570     Section::Section(SectionInfo const& info) :
13571         m_info(info), m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions)) {
13572         m_timer.start();
13573     }
13574
13575     Section::~Section() {
13576         if (m_sectionIncluded) {
13577             SectionEndInfo endInfo{m_info, m_assertions, m_timer.getElapsedSeconds()};
13578             if (uncaught_exceptions())
13579                 getResultCapture().sectionEndedEarly(endInfo);
13580             else
13581                 getResultCapture().sectionEnded(endInfo);
13582         }
13583     }
13584
13585     // This indicates whether the section should be executed or not
13586     Section::operator bool() const { return m_sectionIncluded; }
13587
13588 } // end namespace Catch
13589 // end catch_section.cpp
13590 // start catch_section_info.cpp
13591
13592 namespace Catch {
13593
13594     SectionInfo::SectionInfo(SourceLineInfo const& _lineInfo, std::string const& _name) :
13595         name(_name), lineInfo(_lineInfo) {}
13596
13597 } // end namespace Catch
13598 // end catch_section_info.cpp
13599 // start catch_session.cpp
13600
13601 // start catch_session.h
13602
13603 #include <memory>
13604
13605 namespace Catch {
13606
13607     class Session : NonCopyable {
13608     public:
13609         Session();
13610         ~Session() override;
13611
13612         void showHelp() const;
13613         void libIdentify();
13614
13615         int applyCommandLine(int argc, char const* const* argv);
13616 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13617         int applyCommandLine(int argc, wchar_t const* const* argv);
13618 #endif
13619
13620         void useConfigData(ConfigData const& configData);
13621
13622         template <typename CharT> int run(int argc, CharT const* const argv[]) {
13623             if (m_startupExceptions)
13624                 return 1;
13625             int returnCode = applyCommandLine(argc, argv);
13626             if (returnCode == 0)
13627                 returnCode = run();
13628             return returnCode;
13629         }
13630
13631         int run();
13632
13633         clara::Parser const& cli() const;
13634         void cli(clara::Parser const& newParser);
13635         ConfigData& configData();
13636         Config& config();
13637
13638     private:
13639         int runInternal();
13640
13641         clara::Parser m_cli;
13642         ConfigData m_configData;
13643         std::shared_ptr<Config> m_config;
13644         bool m_startupExceptions = false;
13645     };
13646
13647 } // end namespace Catch
13648
13649 // end catch_session.h
13650 // start catch_version.h
13651
13652 #include <iosfwd>
13653
13654 namespace Catch {
13655
13656     // Versioning information
13657     struct Version {
13658         Version(Version const&) = delete;
13659         Version& operator=(Version const&) = delete;
13660         Version(unsigned int _majorVersion,
13661                 unsigned int _minorVersion,
13662                 unsigned int _patchNumber,
13663                 char const* const _branchName,
13664                 unsigned int _buildNumber);
13665
13666         unsigned int const majorVersion;
13667         unsigned int const minorVersion;
13668         unsigned int const patchNumber;
13669
13670         // buildNumber is only used if branchName is not null
13671         char const* const branchName;
13672         unsigned int const buildNumber;
13673
13674         friend std::ostream& operator<<(std::ostream& os, Version const& version);
13675     };
13676
13677     Version const& libraryVersion();
13678 } // namespace Catch
13679
13680 // end catch_version.h
13681 #include <cstdlib>
13682 #include <iomanip>
13683 #include <set>
13684 #include <iterator>
13685
13686 namespace Catch {
13687
13688     namespace {
13689         const int MaxExitCode = 255;
13690
13691         IStreamingReporterPtr createReporter(std::string const& reporterName,
13692                                              IConfigPtr const& config) {
13693             auto reporter =
13694                 Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13695             CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13696
13697             return reporter;
13698         }
13699
13700         IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13701             if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13702                 return createReporter(config->getReporterName(), config);
13703             }
13704
13705             // On older platforms, returning std::unique_ptr<ListeningReporter>
13706             // when the return type is std::unique_ptr<IStreamingReporter>
13707             // doesn't compile without a std::move call. However, this causes
13708             // a warning on newer platforms. Thus, we have to work around
13709             // it a bit and downcast the pointer manually.
13710             auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13711             auto& multi = static_cast<ListeningReporter&>(*ret);
13712             auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13713             for (auto const& listener : listeners) {
13714                 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13715             }
13716             multi.addReporter(createReporter(config->getReporterName(), config));
13717             return ret;
13718         }
13719
13720         class TestGroup {
13721         public:
13722             explicit TestGroup(std::shared_ptr<Config> const& config) :
13723                 m_config{config}, m_context{config, makeReporter(config)} {
13724                 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13725                 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13726                 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13727
13728                 if (m_matches.empty() && invalidArgs.empty()) {
13729                     for (auto const& test : allTestCases)
13730                         if (!test.isHidden())
13731                             m_tests.emplace(&test);
13732                 } else {
13733                     for (auto const& match : m_matches)
13734                         m_tests.insert(match.tests.begin(), match.tests.end());
13735                 }
13736             }
13737
13738             Totals execute() {
13739                 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13740                 Totals totals;
13741                 m_context.testGroupStarting(m_config->name(), 1, 1);
13742                 for (auto const& testCase : m_tests) {
13743                     if (!m_context.aborting())
13744                         totals += m_context.runTest(*testCase);
13745                     else
13746                         m_context.reporter().skipTest(*testCase);
13747                 }
13748
13749                 for (auto const& match : m_matches) {
13750                     if (match.tests.empty()) {
13751                         m_context.reporter().noMatchingTestCases(match.name);
13752                         totals.error = -1;
13753                     }
13754                 }
13755
13756                 if (!invalidArgs.empty()) {
13757                     for (auto const& invalidArg : invalidArgs)
13758                         m_context.reporter().reportInvalidArguments(invalidArg);
13759                 }
13760
13761                 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13762                 return totals;
13763             }
13764
13765         private:
13766             using Tests = std::set<TestCase const*>;
13767
13768             std::shared_ptr<Config> m_config;
13769             RunContext m_context;
13770             Tests m_tests;
13771             TestSpec::Matches m_matches;
13772         };
13773
13774         void applyFilenamesAsTags(Catch::IConfig const& config) {
13775             auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13776             for (auto& testCase : tests) {
13777                 auto tags = testCase.tags;
13778
13779                 std::string filename = testCase.lineInfo.file;
13780                 auto lastSlash = filename.find_last_of("\\/");
13781                 if (lastSlash != std::string::npos) {
13782                     filename.erase(0, lastSlash);
13783                     filename[0] = '#';
13784                 }
13785
13786                 auto lastDot = filename.find_last_of('.');
13787                 if (lastDot != std::string::npos) {
13788                     filename.erase(lastDot);
13789                 }
13790
13791                 tags.push_back(std::move(filename));
13792                 setTags(testCase, tags);
13793             }
13794         }
13795
13796     } // namespace
13797
13798     Session::Session() {
13799         static bool alreadyInstantiated = false;
13800         if (alreadyInstantiated) {
13801             CATCH_TRY {
13802                 CATCH_INTERNAL_ERROR("Only one instance of Catch::Session can ever be used");
13803             }
13804             CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13805         }
13806
13807         // There cannot be exceptions at startup in no-exception mode.
13808 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13809         const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13810         if (!exceptions.empty()) {
13811             config();
13812             getCurrentMutableContext().setConfig(m_config);
13813
13814             m_startupExceptions = true;
13815             Colour colourGuard(Colour::Red);
13816             Catch::cerr() << "Errors occurred during startup!" << '\n';
13817             // iterate over all exceptions and notify user
13818             for (const auto& ex_ptr : exceptions) {
13819                 try {
13820                     std::rethrow_exception(ex_ptr);
13821                 } catch (std::exception const& ex) {
13822                     Catch::cerr() << Column(ex.what()).indent(2) << '\n';
13823                 }
13824             }
13825         }
13826 #endif
13827
13828         alreadyInstantiated = true;
13829         m_cli = makeCommandLineParser(m_configData);
13830     }
13831     Session::~Session() { Catch::cleanUp(); }
13832
13833     void Session::showHelp() const {
13834         Catch::cout() << "\nCatch v" << libraryVersion() << "\n"
13835                       << m_cli << std::endl
13836                       << "For more detailed usage please see the project docs\n"
13837                       << std::endl;
13838     }
13839     void Session::libIdentify() {
13840         Catch::cout() << std::left << std::setw(16) << "description: "
13841                       << "A Catch2 test executable\n"
13842                       << std::left << std::setw(16) << "category: "
13843                       << "testframework\n"
13844                       << std::left << std::setw(16) << "framework: "
13845                       << "Catch Test\n"
13846                       << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13847     }
13848
13849     int Session::applyCommandLine(int argc, char const* const* argv) {
13850         if (m_startupExceptions)
13851             return 1;
13852
13853         auto result = m_cli.parse(clara::Args(argc, argv));
13854         if (!result) {
13855             config();
13856             getCurrentMutableContext().setConfig(m_config);
13857             Catch::cerr() << Colour(Colour::Red) << "\nError(s) in input:\n"
13858                           << Column(result.errorMessage()).indent(2) << "\n\n";
13859             Catch::cerr() << "Run with -? for usage\n" << std::endl;
13860             return MaxExitCode;
13861         }
13862
13863         if (m_configData.showHelp)
13864             showHelp();
13865         if (m_configData.libIdentify)
13866             libIdentify();
13867         m_config.reset();
13868         return 0;
13869     }
13870
13871 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13872     int Session::applyCommandLine(int argc, wchar_t const* const* argv) {
13873
13874         char** utf8Argv = new char*[argc];
13875
13876         for (int i = 0; i < argc; ++i) {
13877             int bufSize =
13878                 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);
13879
13880             utf8Argv[i] = new char[bufSize];
13881
13882             WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr);
13883         }
13884
13885         int returnCode = applyCommandLine(argc, utf8Argv);
13886
13887         for (int i = 0; i < argc; ++i)
13888             delete[] utf8Argv[i];
13889
13890         delete[] utf8Argv;
13891
13892         return returnCode;
13893     }
13894 #endif
13895
13896     void Session::useConfigData(ConfigData const& configData) {
13897         m_configData = configData;
13898         m_config.reset();
13899     }
13900
13901     int Session::run() {
13902         if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) {
13903             Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13904             static_cast<void>(std::getchar());
13905         }
13906         int exitCode = runInternal();
13907         if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) {
13908             Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode
13909                           << std::endl;
13910             static_cast<void>(std::getchar());
13911         }
13912         return exitCode;
13913     }
13914
13915     clara::Parser const& Session::cli() const { return m_cli; }
13916     void Session::cli(clara::Parser const& newParser) { m_cli = newParser; }
13917     ConfigData& Session::configData() { return m_configData; }
13918     Config& Session::config() {
13919         if (!m_config)
13920             m_config = std::make_shared<Config>(m_configData);
13921         return *m_config;
13922     }
13923
13924     int Session::runInternal() {
13925         if (m_startupExceptions)
13926             return 1;
13927
13928         if (m_configData.showHelp || m_configData.libIdentify) {
13929             return 0;
13930         }
13931
13932         CATCH_TRY {
13933             config(); // Force config to be constructed
13934
13935             seedRng(*m_config);
13936
13937             if (m_configData.filenamesAsTags)
13938                 applyFilenamesAsTags(*m_config);
13939
13940             // Handle list request
13941             if (Option<std::size_t> listed = list(m_config))
13942                 return static_cast<int>(*listed);
13943
13944             TestGroup tests{m_config};
13945             auto const totals = tests.execute();
13946
13947             if (m_config->warnAboutNoTests() && totals.error == -1)
13948                 return 2;
13949
13950             // Note that on unices only the lower 8 bits are usually used,
13951             // clamping the return value to 255 prevents false negative when
13952             // some multiple of 256 tests has failed
13953             return (std::min)(MaxExitCode,
13954                               (std::max)(totals.error, static_cast<int>(totals.assertions.failed)));
13955         }
13956 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13957         catch (std::exception& ex) {
13958             Catch::cerr() << ex.what() << std::endl;
13959             return MaxExitCode;
13960         }
13961 #endif
13962     }
13963
13964 } // end namespace Catch
13965 // end catch_session.cpp
13966 // start catch_singletons.cpp
13967
13968 #include <vector>
13969
13970 namespace Catch {
13971
13972     namespace {
13973         static auto getSingletons() -> std::vector<ISingleton*>*& {
13974             static std::vector<ISingleton*>* g_singletons = nullptr;
13975             if (!g_singletons)
13976                 g_singletons = new std::vector<ISingleton*>();
13977             return g_singletons;
13978         }
13979     } // namespace
13980
13981     ISingleton::~ISingleton() {}
13982
13983     void addSingleton(ISingleton* singleton) { getSingletons()->push_back(singleton); }
13984     void cleanupSingletons() {
13985         auto& singletons = getSingletons();
13986         for (auto singleton : *singletons)
13987             delete singleton;
13988         delete singletons;
13989         singletons = nullptr;
13990     }
13991
13992 } // namespace Catch
13993 // end catch_singletons.cpp
13994 // start catch_startup_exception_registry.cpp
13995
13996 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13997 namespace Catch {
13998     void StartupExceptionRegistry::add(std::exception_ptr const& exception) noexcept {
13999         CATCH_TRY { m_exceptions.push_back(exception); }
14000         CATCH_CATCH_ALL {
14001             // If we run out of memory during start-up there's really not a lot
14002             // more we can do about it
14003             std::terminate();
14004         }
14005     }
14006
14007     std::vector<std::exception_ptr> const&
14008     StartupExceptionRegistry::getExceptions() const noexcept {
14009         return m_exceptions;
14010     }
14011
14012 } // end namespace Catch
14013 #endif
14014 // end catch_startup_exception_registry.cpp
14015 // start catch_stream.cpp
14016
14017 #include <cstdio>
14018 #include <iostream>
14019 #include <fstream>
14020 #include <sstream>
14021 #include <vector>
14022 #include <memory>
14023
14024 namespace Catch {
14025
14026     Catch::IStream::~IStream() = default;
14027
14028     namespace Detail {
14029         namespace {
14030             template <typename WriterF, std::size_t bufferSize = 256>
14031             class StreamBufImpl : public std::streambuf {
14032                 char data[bufferSize];
14033                 WriterF m_writer;
14034
14035             public:
14036                 StreamBufImpl() { setp(data, data + sizeof(data)); }
14037
14038                 ~StreamBufImpl() noexcept { StreamBufImpl::sync(); }
14039
14040             private:
14041                 int overflow(int c) override {
14042                     sync();
14043
14044                     if (c != EOF) {
14045                         if (pbase() == epptr())
14046                             m_writer(std::string(1, static_cast<char>(c)));
14047                         else
14048                             sputc(static_cast<char>(c));
14049                     }
14050                     return 0;
14051                 }
14052
14053                 int sync() override {
14054                     if (pbase() != pptr()) {
14055                         m_writer(std::string(
14056                             pbase(), static_cast<std::string::size_type>(pptr() - pbase())));
14057                         setp(pbase(), epptr());
14058                     }
14059                     return 0;
14060                 }
14061             };
14062
14063             ///////////////////////////////////////////////////////////////////////////
14064
14065             struct OutputDebugWriter {
14066
14067                 void operator()(std::string const& str) { writeToDebugConsole(str); }
14068             };
14069
14070             ///////////////////////////////////////////////////////////////////////////
14071
14072             class FileStream : public IStream {
14073                 mutable std::ofstream m_ofs;
14074
14075             public:
14076                 FileStream(StringRef filename) {
14077                     m_ofs.open(filename.c_str());
14078                     CATCH_ENFORCE(!m_ofs.fail(), "Unable to open file: '" << filename << "'");
14079                 }
14080                 ~FileStream() override = default;
14081
14082             public: // IStream
14083                 std::ostream& stream() const override { return m_ofs; }
14084             };
14085
14086             ///////////////////////////////////////////////////////////////////////////
14087
14088             class CoutStream : public IStream {
14089                 mutable std::ostream m_os;
14090
14091             public:
14092                 // Store the streambuf from cout up-front because
14093                 // cout may get redirected when running tests
14094                 CoutStream() : m_os(Catch::cout().rdbuf()) {}
14095                 ~CoutStream() override = default;
14096
14097             public: // IStream
14098                 std::ostream& stream() const override { return m_os; }
14099             };
14100
14101             ///////////////////////////////////////////////////////////////////////////
14102
14103             class DebugOutStream : public IStream {
14104                 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
14105                 mutable std::ostream m_os;
14106
14107             public:
14108                 DebugOutStream() :
14109                     m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), m_os(m_streamBuf.get()) {}
14110
14111                 ~DebugOutStream() override = default;
14112
14113             public: // IStream
14114                 std::ostream& stream() const override { return m_os; }
14115             };
14116
14117         } // namespace
14118     }     // namespace Detail
14119
14120     ///////////////////////////////////////////////////////////////////////////
14121
14122     auto makeStream(StringRef const& filename) -> IStream const* {
14123         if (filename.empty())
14124             return new Detail::CoutStream();
14125         else if (filename[0] == '%') {
14126             if (filename == "%debug")
14127                 return new Detail::DebugOutStream();
14128             else
14129                 CATCH_ERROR("Unrecognised stream: '" << filename << "'");
14130         } else
14131             return new Detail::FileStream(filename);
14132     }
14133
14134     // This class encapsulates the idea of a pool of ostringstreams that can be
14135     // reused.
14136     struct StringStreams {
14137         std::vector<std::unique_ptr<std::ostringstream>> m_streams;
14138         std::vector<std::size_t> m_unused;
14139         std::ostringstream m_referenceStream; // Used for copy state/ flags from
14140
14141         auto add() -> std::size_t {
14142             if (m_unused.empty()) {
14143                 m_streams.push_back(std::unique_ptr<std::ostringstream>(new std::ostringstream));
14144                 return m_streams.size() - 1;
14145             } else {
14146                 auto index = m_unused.back();
14147                 m_unused.pop_back();
14148                 return index;
14149             }
14150         }
14151
14152         void release(std::size_t index) {
14153             m_streams[index]->copyfmt(m_referenceStream); // Restore initial flags and other state
14154             m_unused.push_back(index);
14155         }
14156     };
14157
14158     ReusableStringStream::ReusableStringStream() :
14159         m_index(Singleton<StringStreams>::getMutable().add()),
14160         m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get()) {}
14161
14162     ReusableStringStream::~ReusableStringStream() {
14163         static_cast<std::ostringstream*>(m_oss)->str("");
14164         m_oss->clear();
14165         Singleton<StringStreams>::getMutable().release(m_index);
14166     }
14167
14168     auto ReusableStringStream::str() const -> std::string {
14169         return static_cast<std::ostringstream*>(m_oss)->str();
14170     }
14171
14172     ///////////////////////////////////////////////////////////////////////////
14173
14174 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these
14175                               // functions
14176     std::ostream& cout() { return std::cout; }
14177     std::ostream& cerr() { return std::cerr; }
14178     std::ostream& clog() { return std::clog; }
14179 #endif
14180 } // namespace Catch
14181 // end catch_stream.cpp
14182 // start catch_string_manip.cpp
14183
14184 #include <algorithm>
14185 #include <ostream>
14186 #include <cstring>
14187 #include <cctype>
14188 #include <vector>
14189
14190 namespace Catch {
14191
14192     namespace {
14193         char toLowerCh(char c) {
14194             return static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
14195         }
14196     } // namespace
14197
14198     bool startsWith(std::string const& s, std::string const& prefix) {
14199         return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
14200     }
14201     bool startsWith(std::string const& s, char prefix) { return !s.empty() && s[0] == prefix; }
14202     bool endsWith(std::string const& s, std::string const& suffix) {
14203         return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
14204     }
14205     bool endsWith(std::string const& s, char suffix) {
14206         return !s.empty() && s[s.size() - 1] == suffix;
14207     }
14208     bool contains(std::string const& s, std::string const& infix) {
14209         return s.find(infix) != std::string::npos;
14210     }
14211     void toLowerInPlace(std::string& s) {
14212         std::transform(s.begin(), s.end(), s.begin(), toLowerCh);
14213     }
14214     std::string toLower(std::string const& s) {
14215         std::string lc = s;
14216         toLowerInPlace(lc);
14217         return lc;
14218     }
14219     std::string trim(std::string const& str) {
14220         static char const* whitespaceChars = "\n\r\t ";
14221         std::string::size_type start = str.find_first_not_of(whitespaceChars);
14222         std::string::size_type end = str.find_last_not_of(whitespaceChars);
14223
14224         return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
14225     }
14226
14227     StringRef trim(StringRef ref) {
14228         const auto is_ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
14229         size_t real_begin = 0;
14230         while (real_begin < ref.size() && is_ws(ref[real_begin])) {
14231             ++real_begin;
14232         }
14233         size_t real_end = ref.size();
14234         while (real_end > real_begin && is_ws(ref[real_end - 1])) {
14235             --real_end;
14236         }
14237
14238         return ref.substr(real_begin, real_end - real_begin);
14239     }
14240
14241     bool
14242     replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis) {
14243         bool replaced = false;
14244         std::size_t i = str.find(replaceThis);
14245         while (i != std::string::npos) {
14246             replaced = true;
14247             str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size());
14248             if (i < str.size() - withThis.size())
14249                 i = str.find(replaceThis, i + withThis.size());
14250             else
14251                 i = std::string::npos;
14252         }
14253         return replaced;
14254     }
14255
14256     std::vector<StringRef> splitStringRef(StringRef str, char delimiter) {
14257         std::vector<StringRef> subStrings;
14258         std::size_t start = 0;
14259         for (std::size_t pos = 0; pos < str.size(); ++pos) {
14260             if (str[pos] == delimiter) {
14261                 if (pos - start > 1)
14262                     subStrings.push_back(str.substr(start, pos - start));
14263                 start = pos + 1;
14264             }
14265         }
14266         if (start < str.size())
14267             subStrings.push_back(str.substr(start, str.size() - start));
14268         return subStrings;
14269     }
14270
14271     pluralise::pluralise(std::size_t count, std::string const& label) :
14272         m_count(count), m_label(label) {}
14273
14274     std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser) {
14275         os << pluraliser.m_count << ' ' << pluraliser.m_label;
14276         if (pluraliser.m_count != 1)
14277             os << 's';
14278         return os;
14279     }
14280
14281 } // namespace Catch
14282 // end catch_string_manip.cpp
14283 // start catch_stringref.cpp
14284
14285 #include <algorithm>
14286 #include <ostream>
14287 #include <cstring>
14288 #include <cstdint>
14289
14290 namespace Catch {
14291     StringRef::StringRef(char const* rawChars) noexcept :
14292         StringRef(rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars))) {}
14293
14294     auto StringRef::c_str() const -> char const* {
14295         CATCH_ENFORCE(isNullTerminated(),
14296                       "Called StringRef::c_str() on a non-null-terminated instance");
14297         return m_start;
14298     }
14299     auto StringRef::data() const noexcept -> char const* { return m_start; }
14300
14301     auto StringRef::substr(size_type start, size_type size) const noexcept -> StringRef {
14302         if (start < m_size) {
14303             return StringRef(m_start + start, (std::min)(m_size - start, size));
14304         } else {
14305             return StringRef();
14306         }
14307     }
14308     auto StringRef::operator==(StringRef const& other) const noexcept -> bool {
14309         return m_size == other.m_size && (std::memcmp(m_start, other.m_start, m_size) == 0);
14310     }
14311
14312     auto operator<<(std::ostream& os, StringRef const& str) -> std::ostream& {
14313         return os.write(str.data(), str.size());
14314     }
14315
14316     auto operator+=(std::string& lhs, StringRef const& rhs) -> std::string& {
14317         lhs.append(rhs.data(), rhs.size());
14318         return lhs;
14319     }
14320
14321 } // namespace Catch
14322 // end catch_stringref.cpp
14323 // start catch_tag_alias.cpp
14324
14325 namespace Catch {
14326     TagAlias::TagAlias(std::string const& _tag, SourceLineInfo _lineInfo) :
14327         tag(_tag), lineInfo(_lineInfo) {}
14328 } // namespace Catch
14329 // end catch_tag_alias.cpp
14330 // start catch_tag_alias_autoregistrar.cpp
14331
14332 namespace Catch {
14333
14334     RegistrarForTagAliases::RegistrarForTagAliases(char const* alias,
14335                                                    char const* tag,
14336                                                    SourceLineInfo const& lineInfo) {
14337         CATCH_TRY { getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); }
14338         CATCH_CATCH_ALL {
14339             // Do not throw when constructing global objects, instead register
14340             // the exception to be processed later
14341             getMutableRegistryHub().registerStartupException();
14342         }
14343     }
14344
14345 } // namespace Catch
14346 // end catch_tag_alias_autoregistrar.cpp
14347 // start catch_tag_alias_registry.cpp
14348
14349 #include <sstream>
14350
14351 namespace Catch {
14352
14353     TagAliasRegistry::~TagAliasRegistry() {}
14354
14355     TagAlias const* TagAliasRegistry::find(std::string const& alias) const {
14356         auto it = m_registry.find(alias);
14357         if (it != m_registry.end())
14358             return &(it->second);
14359         else
14360             return nullptr;
14361     }
14362
14363     std::string TagAliasRegistry::expandAliases(std::string const& unexpandedTestSpec) const {
14364         std::string expandedTestSpec = unexpandedTestSpec;
14365         for (auto const& registryKvp : m_registry) {
14366             std::size_t pos = expandedTestSpec.find(registryKvp.first);
14367             if (pos != std::string::npos) {
14368                 expandedTestSpec = expandedTestSpec.substr(0, pos) + registryKvp.second.tag +
14369                                    expandedTestSpec.substr(pos + registryKvp.first.size());
14370             }
14371         }
14372         return expandedTestSpec;
14373     }
14374
14375     void TagAliasRegistry::add(std::string const& alias,
14376                                std::string const& tag,
14377                                SourceLineInfo const& lineInfo) {
14378         CATCH_ENFORCE(startsWith(alias, "[@") && endsWith(alias, ']'),
14379                       "error: tag alias, '" << alias << "' is not of the form [@alias name].\n"
14380                                             << lineInfo);
14381
14382         CATCH_ENFORCE(m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14383                       "error: tag alias, '" << alias << "' already registered.\n"
14384                                             << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14385                                             << "\tRedefined at: " << lineInfo);
14386     }
14387
14388     ITagAliasRegistry::~ITagAliasRegistry() {}
14389
14390     ITagAliasRegistry const& ITagAliasRegistry::get() {
14391         return getRegistryHub().getTagAliasRegistry();
14392     }
14393
14394 } // end namespace Catch
14395 // end catch_tag_alias_registry.cpp
14396 // start catch_test_case_info.cpp
14397
14398 #include <cctype>
14399 #include <exception>
14400 #include <algorithm>
14401 #include <sstream>
14402
14403 namespace Catch {
14404
14405     namespace {
14406         TestCaseInfo::SpecialProperties parseSpecialTag(std::string const& tag) {
14407             if (startsWith(tag, '.') || tag == "!hide")
14408                 return TestCaseInfo::IsHidden;
14409             else if (tag == "!throws")
14410                 return TestCaseInfo::Throws;
14411             else if (tag == "!shouldfail")
14412                 return TestCaseInfo::ShouldFail;
14413             else if (tag == "!mayfail")
14414                 return TestCaseInfo::MayFail;
14415             else if (tag == "!nonportable")
14416                 return TestCaseInfo::NonPortable;
14417             else if (tag == "!benchmark")
14418                 return static_cast<TestCaseInfo::SpecialProperties>(TestCaseInfo::Benchmark |
14419                                                                     TestCaseInfo::IsHidden);
14420             else
14421                 return TestCaseInfo::None;
14422         }
14423         bool isReservedTag(std::string const& tag) {
14424             return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 &&
14425                    !std::isalnum(static_cast<unsigned char>(tag[0]));
14426         }
14427         void enforceNotReservedTag(std::string const& tag, SourceLineInfo const& _lineInfo) {
14428             CATCH_ENFORCE(!isReservedTag(tag),
14429                           "Tag name: [" << tag << "] is not allowed.\n"
14430                                         << "Tag names starting with non alphanumeric "
14431                                            "characters are reserved\n"
14432                                         << _lineInfo);
14433         }
14434     } // namespace
14435
14436     TestCase makeTestCase(ITestInvoker* _testCase,
14437                           std::string const& _className,
14438                           NameAndTags const& nameAndTags,
14439                           SourceLineInfo const& _lineInfo) {
14440         bool isHidden = false;
14441
14442         // Parse out tags
14443         std::vector<std::string> tags;
14444         std::string desc, tag;
14445         bool inTag = false;
14446         for (char c : nameAndTags.tags) {
14447             if (!inTag) {
14448                 if (c == '[')
14449                     inTag = true;
14450                 else
14451                     desc += c;
14452             } else {
14453                 if (c == ']') {
14454                     TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag);
14455                     if ((prop & TestCaseInfo::IsHidden) != 0)
14456                         isHidden = true;
14457                     else if (prop == TestCaseInfo::None)
14458                         enforceNotReservedTag(tag, _lineInfo);
14459
14460                     // Merged hide tags like `[.approvals]` should be added as
14461                     // `[.][approvals]`. The `[.]` is added at later point, so
14462                     // we only strip the prefix
14463                     if (startsWith(tag, '.') && tag.size() > 1) {
14464                         tag.erase(0, 1);
14465                     }
14466                     tags.push_back(tag);
14467                     tag.clear();
14468                     inTag = false;
14469                 } else
14470                     tag += c;
14471             }
14472         }
14473         if (isHidden) {
14474             // Add all "hidden" tags to make them behave identically
14475             tags.insert(tags.end(), {".", "!hide"});
14476         }
14477
14478         TestCaseInfo info(
14479             static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo);
14480         return TestCase(_testCase, std::move(info));
14481     }
14482
14483     void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags) {
14484         std::sort(begin(tags), end(tags));
14485         tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14486         testCaseInfo.lcaseTags.clear();
14487
14488         for (auto const& tag : tags) {
14489             std::string lcaseTag = toLower(tag);
14490             testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>(
14491                 testCaseInfo.properties | parseSpecialTag(lcaseTag));
14492             testCaseInfo.lcaseTags.push_back(lcaseTag);
14493         }
14494         testCaseInfo.tags = std::move(tags);
14495     }
14496
14497     TestCaseInfo::TestCaseInfo(std::string const& _name,
14498                                std::string const& _className,
14499                                std::string const& _description,
14500                                std::vector<std::string> const& _tags,
14501                                SourceLineInfo const& _lineInfo) :
14502         name(_name),
14503         className(_className),
14504         description(_description),
14505         lineInfo(_lineInfo),
14506         properties(None) {
14507         setTags(*this, _tags);
14508     }
14509
14510     bool TestCaseInfo::isHidden() const { return (properties & IsHidden) != 0; }
14511     bool TestCaseInfo::throws() const { return (properties & Throws) != 0; }
14512     bool TestCaseInfo::okToFail() const { return (properties & (ShouldFail | MayFail)) != 0; }
14513     bool TestCaseInfo::expectedToFail() const { return (properties & (ShouldFail)) != 0; }
14514
14515     std::string TestCaseInfo::tagsAsString() const {
14516         std::string ret;
14517         // '[' and ']' per tag
14518         std::size_t full_size = 2 * tags.size();
14519         for (const auto& tag : tags) {
14520             full_size += tag.size();
14521         }
14522         ret.reserve(full_size);
14523         for (const auto& tag : tags) {
14524             ret.push_back('[');
14525             ret.append(tag);
14526             ret.push_back(']');
14527         }
14528
14529         return ret;
14530     }
14531
14532     TestCase::TestCase(ITestInvoker* testCase, TestCaseInfo&& info) :
14533         TestCaseInfo(std::move(info)), test(testCase) {}
14534
14535     TestCase TestCase::withName(std::string const& _newName) const {
14536         TestCase other(*this);
14537         other.name = _newName;
14538         return other;
14539     }
14540
14541     void TestCase::invoke() const { test->invoke(); }
14542
14543     bool TestCase::operator==(TestCase const& other) const {
14544         return test.get() == other.test.get() && name == other.name && className == other.className;
14545     }
14546
14547     bool TestCase::operator<(TestCase const& other) const { return name < other.name; }
14548
14549     TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; }
14550
14551 } // end namespace Catch
14552 // end catch_test_case_info.cpp
14553 // start catch_test_case_registry_impl.cpp
14554
14555 #include <algorithm>
14556 #include <sstream>
14557
14558 namespace Catch {
14559
14560     namespace {
14561         struct TestHasher {
14562             using hash_t = uint64_t;
14563
14564             explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {}
14565
14566             uint32_t operator()(TestCase const& t) const {
14567                 // FNV-1a hash with multiplication fold.
14568                 const hash_t prime = 1099511628211u;
14569                 hash_t hash = 14695981039346656037u;
14570                 for (const char c : t.name) {
14571                     hash ^= c;
14572                     hash *= prime;
14573                 }
14574                 hash ^= m_hashSuffix;
14575                 hash *= prime;
14576                 const uint32_t low{static_cast<uint32_t>(hash)};
14577                 const uint32_t high{static_cast<uint32_t>(hash >> 32)};
14578                 return low * high;
14579             }
14580
14581         private:
14582             hash_t m_hashSuffix;
14583         };
14584     } // end unnamed namespace
14585
14586     std::vector<TestCase> sortTests(IConfig const& config,
14587                                     std::vector<TestCase> const& unsortedTestCases) {
14588         switch (config.runOrder()) {
14589             case RunTests::InDeclarationOrder:
14590                 // already in declaration order
14591                 break;
14592
14593             case RunTests::InLexicographicalOrder: {
14594                 std::vector<TestCase> sorted = unsortedTestCases;
14595                 std::sort(sorted.begin(), sorted.end());
14596                 return sorted;
14597             }
14598
14599             case RunTests::InRandomOrder: {
14600                 seedRng(config);
14601                 TestHasher h{config.rngSeed()};
14602
14603                 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14604                 std::vector<hashedTest> indexed_tests;
14605                 indexed_tests.reserve(unsortedTestCases.size());
14606
14607                 for (auto const& testCase : unsortedTestCases) {
14608                     indexed_tests.emplace_back(h(testCase), &testCase);
14609                 }
14610
14611                 std::sort(indexed_tests.begin(),
14612                           indexed_tests.end(),
14613                           [](hashedTest const& lhs, hashedTest const& rhs) {
14614                               if (lhs.first == rhs.first) {
14615                                   return lhs.second->name < rhs.second->name;
14616                               }
14617                               return lhs.first < rhs.first;
14618                           });
14619
14620                 std::vector<TestCase> sorted;
14621                 sorted.reserve(indexed_tests.size());
14622
14623                 for (auto const& hashed : indexed_tests) {
14624                     sorted.emplace_back(*hashed.second);
14625                 }
14626
14627                 return sorted;
14628             }
14629         }
14630         return unsortedTestCases;
14631     }
14632
14633     bool isThrowSafe(TestCase const& testCase, IConfig const& config) {
14634         return !testCase.throws() || config.allowThrows();
14635     }
14636
14637     bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config) {
14638         return testSpec.matches(testCase) && isThrowSafe(testCase, config);
14639     }
14640
14641     void enforceNoDuplicateTestCases(std::vector<TestCase> const& functions) {
14642         std::set<TestCase> seenFunctions;
14643         for (auto const& function : functions) {
14644             auto prev = seenFunctions.insert(function);
14645             CATCH_ENFORCE(prev.second,
14646                           "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14647                                                  << "\tFirst seen at "
14648                                                  << prev.first->getTestCaseInfo().lineInfo << "\n"
14649                                                  << "\tRedefined at "
14650                                                  << function.getTestCaseInfo().lineInfo);
14651         }
14652     }
14653
14654     std::vector<TestCase> filterTests(std::vector<TestCase> const& testCases,
14655                                       TestSpec const& testSpec,
14656                                       IConfig const& config) {
14657         std::vector<TestCase> filtered;
14658         filtered.reserve(testCases.size());
14659         for (auto const& testCase : testCases) {
14660             if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14661                 (testSpec.hasFilters() && matchTest(testCase, testSpec, config)))
14662             {
14663                 filtered.push_back(testCase);
14664             }
14665         }
14666         return filtered;
14667     }
14668     std::vector<TestCase> const& getAllTestCasesSorted(IConfig const& config) {
14669         return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config);
14670     }
14671
14672     void TestRegistry::registerTest(TestCase const& testCase) {
14673         std::string name = testCase.getTestCaseInfo().name;
14674         if (name.empty()) {
14675             ReusableStringStream rss;
14676             rss << "Anonymous test case " << ++m_unnamedCount;
14677             return registerTest(testCase.withName(rss.str()));
14678         }
14679         m_functions.push_back(testCase);
14680     }
14681
14682     std::vector<TestCase> const& TestRegistry::getAllTests() const { return m_functions; }
14683     std::vector<TestCase> const& TestRegistry::getAllTestsSorted(IConfig const& config) const {
14684         if (m_sortedFunctions.empty())
14685             enforceNoDuplicateTestCases(m_functions);
14686
14687         if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) {
14688             m_sortedFunctions = sortTests(config, m_functions);
14689             m_currentSortOrder = config.runOrder();
14690         }
14691         return m_sortedFunctions;
14692     }
14693
14694     ///////////////////////////////////////////////////////////////////////////
14695     TestInvokerAsFunction::TestInvokerAsFunction(void (*testAsFunction)()) noexcept :
14696         m_testAsFunction(testAsFunction) {}
14697
14698     void TestInvokerAsFunction::invoke() const { m_testAsFunction(); }
14699
14700     std::string extractClassName(StringRef const& classOrQualifiedMethodName) {
14701         std::string className(classOrQualifiedMethodName);
14702         if (startsWith(className, '&')) {
14703             std::size_t lastColons = className.rfind("::");
14704             std::size_t penultimateColons = className.rfind("::", lastColons - 1);
14705             if (penultimateColons == std::string::npos)
14706                 penultimateColons = 1;
14707             className = className.substr(penultimateColons, lastColons - penultimateColons);
14708         }
14709         return className;
14710     }
14711
14712 } // end namespace Catch
14713 // end catch_test_case_registry_impl.cpp
14714 // start catch_test_case_tracker.cpp
14715
14716 #include <algorithm>
14717 #include <cassert>
14718 #include <stdexcept>
14719 #include <memory>
14720 #include <sstream>
14721
14722 #if defined(__clang__)
14723 #pragma clang diagnostic push
14724 #pragma clang diagnostic ignored "-Wexit-time-destructors"
14725 #endif
14726
14727 namespace Catch {
14728     namespace TestCaseTracking {
14729
14730         NameAndLocation::NameAndLocation(std::string const& _name,
14731                                          SourceLineInfo const& _location) :
14732             name(_name), location(_location) {}
14733
14734         ITracker::~ITracker() = default;
14735
14736         ITracker& TrackerContext::startRun() {
14737             m_rootTracker = std::make_shared<SectionTracker>(
14738                 NameAndLocation("{root}", CATCH_INTERNAL_LINEINFO), *this, nullptr);
14739             m_currentTracker = nullptr;
14740             m_runState = Executing;
14741             return *m_rootTracker;
14742         }
14743
14744         void TrackerContext::endRun() {
14745             m_rootTracker.reset();
14746             m_currentTracker = nullptr;
14747             m_runState = NotStarted;
14748         }
14749
14750         void TrackerContext::startCycle() {
14751             m_currentTracker = m_rootTracker.get();
14752             m_runState = Executing;
14753         }
14754         void TrackerContext::completeCycle() { m_runState = CompletedCycle; }
14755
14756         bool TrackerContext::completedCycle() const { return m_runState == CompletedCycle; }
14757         ITracker& TrackerContext::currentTracker() { return *m_currentTracker; }
14758         void TrackerContext::setCurrentTracker(ITracker* tracker) { m_currentTracker = tracker; }
14759
14760         TrackerBase::TrackerBase(NameAndLocation const& nameAndLocation,
14761                                  TrackerContext& ctx,
14762                                  ITracker* parent) :
14763             ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent) {}
14764
14765         bool TrackerBase::isComplete() const {
14766             return m_runState == CompletedSuccessfully || m_runState == Failed;
14767         }
14768         bool TrackerBase::isSuccessfullyCompleted() const {
14769             return m_runState == CompletedSuccessfully;
14770         }
14771         bool TrackerBase::isOpen() const { return m_runState != NotStarted && !isComplete(); }
14772         bool TrackerBase::hasChildren() const { return !m_children.empty(); }
14773
14774         void TrackerBase::addChild(ITrackerPtr const& child) { m_children.push_back(child); }
14775
14776         ITrackerPtr TrackerBase::findChild(NameAndLocation const& nameAndLocation) {
14777             auto it = std::find_if(
14778                 m_children.begin(),
14779                 m_children.end(),
14780                 [&nameAndLocation](ITrackerPtr const& tracker) {
14781                     return tracker->nameAndLocation().location == nameAndLocation.location &&
14782                            tracker->nameAndLocation().name == nameAndLocation.name;
14783                 });
14784             return (it != m_children.end()) ? *it : nullptr;
14785         }
14786         ITracker& TrackerBase::parent() {
14787             assert(m_parent); // Should always be non-null except for root
14788             return *m_parent;
14789         }
14790
14791         void TrackerBase::openChild() {
14792             if (m_runState != ExecutingChildren) {
14793                 m_runState = ExecutingChildren;
14794                 if (m_parent)
14795                     m_parent->openChild();
14796             }
14797         }
14798
14799         bool TrackerBase::isSectionTracker() const { return false; }
14800         bool TrackerBase::isGeneratorTracker() const { return false; }
14801
14802         void TrackerBase::open() {
14803             m_runState = Executing;
14804             moveToThis();
14805             if (m_parent)
14806                 m_parent->openChild();
14807         }
14808
14809         void TrackerBase::close() {
14810
14811             // Close any still open children (e.g. generators)
14812             while (&m_ctx.currentTracker() != this)
14813                 m_ctx.currentTracker().close();
14814
14815             switch (m_runState) {
14816                 case NeedsAnotherRun:
14817                     break;
14818
14819                 case Executing:
14820                     m_runState = CompletedSuccessfully;
14821                     break;
14822                 case ExecutingChildren:
14823                     if (std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t) {
14824                             return t->isComplete();
14825                         }))
14826                         m_runState = CompletedSuccessfully;
14827                     break;
14828
14829                 case NotStarted:
14830                 case CompletedSuccessfully:
14831                 case Failed:
14832                     CATCH_INTERNAL_ERROR("Illogical state: " << m_runState);
14833
14834                 default:
14835                     CATCH_INTERNAL_ERROR("Unknown state: " << m_runState);
14836             }
14837             moveToParent();
14838             m_ctx.completeCycle();
14839         }
14840         void TrackerBase::fail() {
14841             m_runState = Failed;
14842             if (m_parent)
14843                 m_parent->markAsNeedingAnotherRun();
14844             moveToParent();
14845             m_ctx.completeCycle();
14846         }
14847         void TrackerBase::markAsNeedingAnotherRun() { m_runState = NeedsAnotherRun; }
14848
14849         void TrackerBase::moveToParent() {
14850             assert(m_parent);
14851             m_ctx.setCurrentTracker(m_parent);
14852         }
14853         void TrackerBase::moveToThis() { m_ctx.setCurrentTracker(this); }
14854
14855         SectionTracker::SectionTracker(NameAndLocation const& nameAndLocation,
14856                                        TrackerContext& ctx,
14857                                        ITracker* parent) :
14858             TrackerBase(nameAndLocation, ctx, parent), m_trimmed_name(trim(nameAndLocation.name)) {
14859             if (parent) {
14860                 while (!parent->isSectionTracker())
14861                     parent = &parent->parent();
14862
14863                 SectionTracker& parentSection = static_cast<SectionTracker&>(*parent);
14864                 addNextFilters(parentSection.m_filters);
14865             }
14866         }
14867
14868         bool SectionTracker::isComplete() const {
14869             bool complete = true;
14870
14871             if (m_filters.empty() || m_filters[0] == "" ||
14872                 std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end())
14873             {
14874                 complete = TrackerBase::isComplete();
14875             }
14876             return complete;
14877         }
14878
14879         bool SectionTracker::isSectionTracker() const { return true; }
14880
14881         SectionTracker& SectionTracker::acquire(TrackerContext& ctx,
14882                                                 NameAndLocation const& nameAndLocation) {
14883             std::shared_ptr<SectionTracker> section;
14884
14885             ITracker& currentTracker = ctx.currentTracker();
14886             if (ITrackerPtr childTracker = currentTracker.findChild(nameAndLocation)) {
14887                 assert(childTracker);
14888                 assert(childTracker->isSectionTracker());
14889                 section = std::static_pointer_cast<SectionTracker>(childTracker);
14890             } else {
14891                 section = std::make_shared<SectionTracker>(nameAndLocation, ctx, &currentTracker);
14892                 currentTracker.addChild(section);
14893             }
14894             if (!ctx.completedCycle())
14895                 section->tryOpen();
14896             return *section;
14897         }
14898
14899         void SectionTracker::tryOpen() {
14900             if (!isComplete())
14901                 open();
14902         }
14903
14904         void SectionTracker::addInitialFilters(std::vector<std::string> const& filters) {
14905             if (!filters.empty()) {
14906                 m_filters.reserve(m_filters.size() + filters.size() + 2);
14907                 m_filters.emplace_back(""); // Root - should never be consulted
14908                 m_filters.emplace_back(""); // Test Case - not a section filter
14909                 m_filters.insert(m_filters.end(), filters.begin(), filters.end());
14910             }
14911         }
14912         void SectionTracker::addNextFilters(std::vector<std::string> const& filters) {
14913             if (filters.size() > 1)
14914                 m_filters.insert(m_filters.end(), filters.begin() + 1, filters.end());
14915         }
14916
14917         std::vector<std::string> const& SectionTracker::getFilters() const { return m_filters; }
14918
14919         std::string const& SectionTracker::trimmedName() const { return m_trimmed_name; }
14920
14921     } // namespace TestCaseTracking
14922
14923     using TestCaseTracking::ITracker;
14924     using TestCaseTracking::SectionTracker;
14925     using TestCaseTracking::TrackerContext;
14926
14927 } // namespace Catch
14928
14929 #if defined(__clang__)
14930 #pragma clang diagnostic pop
14931 #endif
14932 // end catch_test_case_tracker.cpp
14933 // start catch_test_registry.cpp
14934
14935 namespace Catch {
14936
14937     auto makeTestInvoker(void (*testAsFunction)()) noexcept -> ITestInvoker* {
14938         return new (std::nothrow) TestInvokerAsFunction(testAsFunction);
14939     }
14940
14941     NameAndTags::NameAndTags(StringRef const& name_, StringRef const& tags_) noexcept :
14942         name(name_), tags(tags_) {}
14943
14944     AutoReg::AutoReg(ITestInvoker* invoker,
14945                      SourceLineInfo const& lineInfo,
14946                      StringRef const& classOrMethod,
14947                      NameAndTags const& nameAndTags) noexcept {
14948         CATCH_TRY {
14949             getMutableRegistryHub().registerTest(
14950                 makeTestCase(invoker, extractClassName(classOrMethod), nameAndTags, lineInfo));
14951         }
14952         CATCH_CATCH_ALL {
14953             // Do not throw when constructing global objects, instead register
14954             // the exception to be processed later
14955             getMutableRegistryHub().registerStartupException();
14956         }
14957     }
14958
14959     AutoReg::~AutoReg() = default;
14960 } // namespace Catch
14961 // end catch_test_registry.cpp
14962 // start catch_test_spec.cpp
14963
14964 #include <algorithm>
14965 #include <string>
14966 #include <vector>
14967 #include <memory>
14968
14969 namespace Catch {
14970
14971     TestSpec::Pattern::Pattern(std::string const& name) : m_name(name) {}
14972
14973     TestSpec::Pattern::~Pattern() = default;
14974
14975     std::string const& TestSpec::Pattern::name() const { return m_name; }
14976
14977     TestSpec::NamePattern::NamePattern(std::string const& name, std::string const& filterString) :
14978         Pattern(filterString), m_wildcardPattern(toLower(name), CaseSensitive::No) {}
14979
14980     bool TestSpec::NamePattern::matches(TestCaseInfo const& testCase) const {
14981         return m_wildcardPattern.matches(testCase.name);
14982     }
14983
14984     TestSpec::TagPattern::TagPattern(std::string const& tag, std::string const& filterString) :
14985         Pattern(filterString), m_tag(toLower(tag)) {}
14986
14987     bool TestSpec::TagPattern::matches(TestCaseInfo const& testCase) const {
14988         return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) !=
14989                end(testCase.lcaseTags);
14990     }
14991
14992     TestSpec::ExcludedPattern::ExcludedPattern(PatternPtr const& underlyingPattern) :
14993         Pattern(underlyingPattern->name()), m_underlyingPattern(underlyingPattern) {}
14994
14995     bool TestSpec::ExcludedPattern::matches(TestCaseInfo const& testCase) const {
14996         return !m_underlyingPattern->matches(testCase);
14997     }
14998
14999     bool TestSpec::Filter::matches(TestCaseInfo const& testCase) const {
15000         return std::all_of(m_patterns.begin(), m_patterns.end(), [&](PatternPtr const& p) {
15001             return p->matches(testCase);
15002         });
15003     }
15004
15005     std::string TestSpec::Filter::name() const {
15006         std::string name;
15007         for (auto const& p : m_patterns)
15008             name += p->name();
15009         return name;
15010     }
15011
15012     bool TestSpec::hasFilters() const { return !m_filters.empty(); }
15013
15014     bool TestSpec::matches(TestCaseInfo const& testCase) const {
15015         return std::any_of(m_filters.begin(), m_filters.end(), [&](Filter const& f) {
15016             return f.matches(testCase);
15017         });
15018     }
15019
15020     TestSpec::Matches TestSpec::matchesByFilter(std::vector<TestCase> const& testCases,
15021                                                 IConfig const& config) const {
15022         Matches matches(m_filters.size());
15023         std::transform(
15024             m_filters.begin(), m_filters.end(), matches.begin(), [&](Filter const& filter) {
15025                 std::vector<TestCase const*> currentMatches;
15026                 for (auto const& test : testCases)
15027                     if (isThrowSafe(test, config) && filter.matches(test))
15028                         currentMatches.emplace_back(&test);
15029                 return FilterMatch{filter.name(), currentMatches};
15030             });
15031         return matches;
15032     }
15033
15034     const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const { return (m_invalidArgs); }
15035
15036 } // namespace Catch
15037 // end catch_test_spec.cpp
15038 // start catch_test_spec_parser.cpp
15039
15040 namespace Catch {
15041
15042     TestSpecParser::TestSpecParser(ITagAliasRegistry const& tagAliases) :
15043         m_tagAliases(&tagAliases) {}
15044
15045     TestSpecParser& TestSpecParser::parse(std::string const& arg) {
15046         m_mode = None;
15047         m_exclusion = false;
15048         m_arg = m_tagAliases->expandAliases(arg);
15049         m_escapeChars.clear();
15050         m_substring.reserve(m_arg.size());
15051         m_patternName.reserve(m_arg.size());
15052         m_realPatternPos = 0;
15053
15054         for (m_pos = 0; m_pos < m_arg.size(); ++m_pos)
15055             // if visitChar fails
15056             if (!visitChar(m_arg[m_pos])) {
15057                 m_testSpec.m_invalidArgs.push_back(arg);
15058                 break;
15059             }
15060         endMode();
15061         return *this;
15062     }
15063     TestSpec TestSpecParser::testSpec() {
15064         addFilter();
15065         return m_testSpec;
15066     }
15067     bool TestSpecParser::visitChar(char c) {
15068         if ((m_mode != EscapedName) && (c == '\\')) {
15069             escape();
15070             addCharToPattern(c);
15071             return true;
15072         } else if ((m_mode != EscapedName) && (c == ',')) {
15073             return separate();
15074         }
15075
15076         switch (m_mode) {
15077             case None:
15078                 if (processNoneChar(c))
15079                     return true;
15080                 break;
15081             case Name:
15082                 processNameChar(c);
15083                 break;
15084             case EscapedName:
15085                 endMode();
15086                 addCharToPattern(c);
15087                 return true;
15088             default:
15089             case Tag:
15090             case QuotedName:
15091                 if (processOtherChar(c))
15092                     return true;
15093                 break;
15094         }
15095
15096         m_substring += c;
15097         if (!isControlChar(c)) {
15098             m_patternName += c;
15099             m_realPatternPos++;
15100         }
15101         return true;
15102     }
15103     // Two of the processing methods return true to signal the caller to return
15104     // without adding the given character to the current pattern strings
15105     bool TestSpecParser::processNoneChar(char c) {
15106         switch (c) {
15107             case ' ':
15108                 return true;
15109             case '~':
15110                 m_exclusion = true;
15111                 return false;
15112             case '[':
15113                 startNewMode(Tag);
15114                 return false;
15115             case '"':
15116                 startNewMode(QuotedName);
15117                 return false;
15118             default:
15119                 startNewMode(Name);
15120                 return false;
15121         }
15122     }
15123     void TestSpecParser::processNameChar(char c) {
15124         if (c == '[') {
15125             if (m_substring == "exclude:")
15126                 m_exclusion = true;
15127             else
15128                 endMode();
15129             startNewMode(Tag);
15130         }
15131     }
15132     bool TestSpecParser::processOtherChar(char c) {
15133         if (!isControlChar(c))
15134             return false;
15135         m_substring += c;
15136         endMode();
15137         return true;
15138     }
15139     void TestSpecParser::startNewMode(Mode mode) { m_mode = mode; }
15140     void TestSpecParser::endMode() {
15141         switch (m_mode) {
15142             case Name:
15143             case QuotedName:
15144                 return addNamePattern();
15145             case Tag:
15146                 return addTagPattern();
15147             case EscapedName:
15148                 revertBackToLastMode();
15149                 return;
15150             case None:
15151             default:
15152                 return startNewMode(None);
15153         }
15154     }
15155     void TestSpecParser::escape() {
15156         saveLastMode();
15157         m_mode = EscapedName;
15158         m_escapeChars.push_back(m_realPatternPos);
15159     }
15160     bool TestSpecParser::isControlChar(char c) const {
15161         switch (m_mode) {
15162             default:
15163                 return false;
15164             case None:
15165                 return c == '~';
15166             case Name:
15167                 return c == '[';
15168             case EscapedName:
15169                 return true;
15170             case QuotedName:
15171                 return c == '"';
15172             case Tag:
15173                 return c == '[' || c == ']';
15174         }
15175     }
15176
15177     void TestSpecParser::addFilter() {
15178         if (!m_currentFilter.m_patterns.empty()) {
15179             m_testSpec.m_filters.push_back(m_currentFilter);
15180             m_currentFilter = TestSpec::Filter();
15181         }
15182     }
15183
15184     void TestSpecParser::saveLastMode() { lastMode = m_mode; }
15185
15186     void TestSpecParser::revertBackToLastMode() { m_mode = lastMode; }
15187
15188     bool TestSpecParser::separate() {
15189         if ((m_mode == QuotedName) || (m_mode == Tag)) {
15190             // invalid argument, signal failure to previous scope.
15191             m_mode = None;
15192             m_pos = m_arg.size();
15193             m_substring.clear();
15194             m_patternName.clear();
15195             m_realPatternPos = 0;
15196             return false;
15197         }
15198         endMode();
15199         addFilter();
15200         return true; // success
15201     }
15202
15203     std::string TestSpecParser::preprocessPattern() {
15204         std::string token = m_patternName;
15205         for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
15206             token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
15207         m_escapeChars.clear();
15208         if (startsWith(token, "exclude:")) {
15209             m_exclusion = true;
15210             token = token.substr(8);
15211         }
15212
15213         m_patternName.clear();
15214         m_realPatternPos = 0;
15215
15216         return token;
15217     }
15218
15219     void TestSpecParser::addNamePattern() {
15220         auto token = preprocessPattern();
15221
15222         if (!token.empty()) {
15223             TestSpec::PatternPtr pattern =
15224                 std::make_shared<TestSpec::NamePattern>(token, m_substring);
15225             if (m_exclusion)
15226                 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15227             m_currentFilter.m_patterns.push_back(pattern);
15228         }
15229         m_substring.clear();
15230         m_exclusion = false;
15231         m_mode = None;
15232     }
15233
15234     void TestSpecParser::addTagPattern() {
15235         auto token = preprocessPattern();
15236
15237         if (!token.empty()) {
15238             // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
15239             // we have to create a separate hide tag and shorten the real one
15240             if (token.size() > 1 && token[0] == '.') {
15241                 token.erase(token.begin());
15242                 TestSpec::PatternPtr pattern =
15243                     std::make_shared<TestSpec::TagPattern>(".", m_substring);
15244                 if (m_exclusion) {
15245                     pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15246                 }
15247                 m_currentFilter.m_patterns.push_back(pattern);
15248             }
15249
15250             TestSpec::PatternPtr pattern =
15251                 std::make_shared<TestSpec::TagPattern>(token, m_substring);
15252
15253             if (m_exclusion) {
15254                 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
15255             }
15256             m_currentFilter.m_patterns.push_back(pattern);
15257         }
15258         m_substring.clear();
15259         m_exclusion = false;
15260         m_mode = None;
15261     }
15262
15263     TestSpec parseTestSpec(std::string const& arg) {
15264         return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec();
15265     }
15266
15267 } // namespace Catch
15268 // end catch_test_spec_parser.cpp
15269 // start catch_timer.cpp
15270
15271 #include <chrono>
15272
15273 static const uint64_t nanosecondsInSecond = 1000000000;
15274
15275 namespace Catch {
15276
15277     auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
15278         return std::chrono::duration_cast<std::chrono::nanoseconds>(
15279                    std::chrono::high_resolution_clock::now().time_since_epoch())
15280             .count();
15281     }
15282
15283     namespace {
15284         auto estimateClockResolution() -> uint64_t {
15285             uint64_t sum = 0;
15286             static const uint64_t iterations = 1000000;
15287
15288             auto startTime = getCurrentNanosecondsSinceEpoch();
15289
15290             for (std::size_t i = 0; i < iterations; ++i) {
15291
15292                 uint64_t ticks;
15293                 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
15294                 do {
15295                     ticks = getCurrentNanosecondsSinceEpoch();
15296                 } while (ticks == baseTicks);
15297
15298                 auto delta = ticks - baseTicks;
15299                 sum += delta;
15300
15301                 // If we have been calibrating for over 3 seconds -- the clock
15302                 // is terrible and we should move on.
15303                 // TBD: How to signal that the measured resolution is probably
15304                 // wrong?
15305                 if (ticks > startTime + 3 * nanosecondsInSecond) {
15306                     return sum / (i + 1u);
15307                 }
15308             }
15309
15310             // We're just taking the mean, here. To do better we could take the
15311             // std. dev and exclude outliers
15312             // - and potentially do more iterations if there's a high variance.
15313             return sum / iterations;
15314         }
15315     } // namespace
15316     auto getEstimatedClockResolution() -> uint64_t {
15317         static auto s_resolution = estimateClockResolution();
15318         return s_resolution;
15319     }
15320
15321     void Timer::start() { m_nanoseconds = getCurrentNanosecondsSinceEpoch(); }
15322     auto Timer::getElapsedNanoseconds() const -> uint64_t {
15323         return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
15324     }
15325     auto Timer::getElapsedMicroseconds() const -> uint64_t {
15326         return getElapsedNanoseconds() / 1000;
15327     }
15328     auto Timer::getElapsedMilliseconds() const -> unsigned int {
15329         return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
15330     }
15331     auto Timer::getElapsedSeconds() const -> double { return getElapsedMicroseconds() / 1000000.0; }
15332
15333 } // namespace Catch
15334 // end catch_timer.cpp
15335 // start catch_tostring.cpp
15336
15337 #if defined(__clang__)
15338 #pragma clang diagnostic push
15339 #pragma clang diagnostic ignored "-Wexit-time-destructors"
15340 #pragma clang diagnostic ignored "-Wglobal-constructors"
15341 #endif
15342
15343 // Enable specific decls locally
15344 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15345 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15346 #endif
15347
15348 #include <cmath>
15349 #include <iomanip>
15350
15351 namespace Catch {
15352
15353     namespace Detail {
15354
15355         const std::string unprintableString = "{?}";
15356
15357         namespace {
15358             const int hexThreshold = 255;
15359
15360             struct Endianness {
15361                 enum Arch { Big, Little };
15362
15363                 static Arch which() {
15364                     int one = 1;
15365                     // If the lowest byte we read is non-zero, we can assume
15366                     // that little endian format is used.
15367                     auto value = *reinterpret_cast<char*>(&one);
15368                     return value ? Little : Big;
15369                 }
15370             };
15371         } // namespace
15372
15373         std::string rawMemoryToString(const void* object, std::size_t size) {
15374             // Reverse order for little endian architectures
15375             int i = 0, end = static_cast<int>(size), inc = 1;
15376             if (Endianness::which() == Endianness::Little) {
15377                 i = end - 1;
15378                 end = inc = -1;
15379             }
15380
15381             unsigned char const* bytes = static_cast<unsigned char const*>(object);
15382             ReusableStringStream rss;
15383             rss << "0x" << std::setfill('0') << std::hex;
15384             for (; i != end; i += inc)
15385                 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15386             return rss.str();
15387         }
15388     } // namespace Detail
15389
15390     template <typename T> std::string fpToString(T value, int precision) {
15391         if (Catch::isnan(value)) {
15392             return "nan";
15393         }
15394
15395         ReusableStringStream rss;
15396         rss << std::setprecision(precision) << std::fixed << value;
15397         std::string d = rss.str();
15398         std::size_t i = d.find_last_not_of('0');
15399         if (i != std::string::npos && i != d.size() - 1) {
15400             if (d[i] == '.')
15401                 i++;
15402             d = d.substr(0, i + 1);
15403         }
15404         return d;
15405     }
15406
15407     //// ======================================================= ////
15408     //
15409     //   Out-of-line defs for full specialization of StringMaker
15410     //
15411     //// ======================================================= ////
15412
15413     std::string StringMaker<std::string>::convert(const std::string& str) {
15414         if (!getCurrentContext().getConfig()->showInvisibles()) {
15415             return '"' + str + '"';
15416         }
15417
15418         std::string s("\"");
15419         for (char c : str) {
15420             switch (c) {
15421                 case '\n':
15422                     s.append("\\n");
15423                     break;
15424                 case '\t':
15425                     s.append("\\t");
15426                     break;
15427                 default:
15428                     s.push_back(c);
15429                     break;
15430             }
15431         }
15432         s.append("\"");
15433         return s;
15434     }
15435
15436 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15437     std::string StringMaker<std::string_view>::convert(std::string_view str) {
15438         return ::Catch::Detail::stringify(std::string{str});
15439     }
15440 #endif
15441
15442     std::string StringMaker<char const*>::convert(char const* str) {
15443         if (str) {
15444             return ::Catch::Detail::stringify(std::string{str});
15445         } else {
15446             return {"{null string}"};
15447         }
15448     }
15449     std::string StringMaker<char*>::convert(char* str) {
15450         if (str) {
15451             return ::Catch::Detail::stringify(std::string{str});
15452         } else {
15453             return {"{null string}"};
15454         }
15455     }
15456
15457 #ifdef CATCH_CONFIG_WCHAR
15458     std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15459         std::string s;
15460         s.reserve(wstr.size());
15461         for (auto c : wstr) {
15462             s += (c <= 0xff) ? static_cast<char>(c) : '?';
15463         }
15464         return ::Catch::Detail::stringify(s);
15465     }
15466
15467 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15468     std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15469         return StringMaker<std::wstring>::convert(std::wstring(str));
15470     }
15471 #endif
15472
15473     std::string StringMaker<wchar_t const*>::convert(wchar_t const* str) {
15474         if (str) {
15475             return ::Catch::Detail::stringify(std::wstring{str});
15476         } else {
15477             return {"{null string}"};
15478         }
15479     }
15480     std::string StringMaker<wchar_t*>::convert(wchar_t* str) {
15481         if (str) {
15482             return ::Catch::Detail::stringify(std::wstring{str});
15483         } else {
15484             return {"{null string}"};
15485         }
15486     }
15487 #endif
15488
15489 #if defined(CATCH_CONFIG_CPP17_BYTE)
15490 #include <cstddef>
15491     std::string StringMaker<std::byte>::convert(std::byte value) {
15492         return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15493     }
15494 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15495
15496     std::string StringMaker<int>::convert(int value) {
15497         return ::Catch::Detail::stringify(static_cast<long long>(value));
15498     }
15499     std::string StringMaker<long>::convert(long value) {
15500         return ::Catch::Detail::stringify(static_cast<long long>(value));
15501     }
15502     std::string StringMaker<long long>::convert(long long value) {
15503         ReusableStringStream rss;
15504         rss << value;
15505         if (value > Detail::hexThreshold) {
15506             rss << " (0x" << std::hex << value << ')';
15507         }
15508         return rss.str();
15509     }
15510
15511     std::string StringMaker<unsigned int>::convert(unsigned int value) {
15512         return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15513     }
15514     std::string StringMaker<unsigned long>::convert(unsigned long value) {
15515         return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15516     }
15517     std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15518         ReusableStringStream rss;
15519         rss << value;
15520         if (value > Detail::hexThreshold) {
15521             rss << " (0x" << std::hex << value << ')';
15522         }
15523         return rss.str();
15524     }
15525
15526     std::string StringMaker<bool>::convert(bool b) { return b ? "true" : "false"; }
15527
15528     std::string StringMaker<signed char>::convert(signed char value) {
15529         if (value == '\r') {
15530             return "'\\r'";
15531         } else if (value == '\f') {
15532             return "'\\f'";
15533         } else if (value == '\n') {
15534             return "'\\n'";
15535         } else if (value == '\t') {
15536             return "'\\t'";
15537         } else if ('\0' <= value && value < ' ') {
15538             return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15539         } else {
15540             char chstr[] = "' '";
15541             chstr[1] = value;
15542             return chstr;
15543         }
15544     }
15545     std::string StringMaker<char>::convert(char c) {
15546         return ::Catch::Detail::stringify(static_cast<signed char>(c));
15547     }
15548     std::string StringMaker<unsigned char>::convert(unsigned char c) {
15549         return ::Catch::Detail::stringify(static_cast<char>(c));
15550     }
15551
15552     std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) { return "nullptr"; }
15553
15554     int StringMaker<float>::precision = 5;
15555
15556     std::string StringMaker<float>::convert(float value) {
15557         return fpToString(value, precision) + 'f';
15558     }
15559
15560     int StringMaker<double>::precision = 10;
15561
15562     std::string StringMaker<double>::convert(double value) { return fpToString(value, precision); }
15563
15564     std::string ratio_string<std::atto>::symbol() { return "a"; }
15565     std::string ratio_string<std::femto>::symbol() { return "f"; }
15566     std::string ratio_string<std::pico>::symbol() { return "p"; }
15567     std::string ratio_string<std::nano>::symbol() { return "n"; }
15568     std::string ratio_string<std::micro>::symbol() { return "u"; }
15569     std::string ratio_string<std::milli>::symbol() { return "m"; }
15570
15571 } // end namespace Catch
15572
15573 #if defined(__clang__)
15574 #pragma clang diagnostic pop
15575 #endif
15576
15577 // end catch_tostring.cpp
15578 // start catch_totals.cpp
15579
15580 namespace Catch {
15581
15582     Counts Counts::operator-(Counts const& other) const {
15583         Counts diff;
15584         diff.passed = passed - other.passed;
15585         diff.failed = failed - other.failed;
15586         diff.failedButOk = failedButOk - other.failedButOk;
15587         return diff;
15588     }
15589
15590     Counts& Counts::operator+=(Counts const& other) {
15591         passed += other.passed;
15592         failed += other.failed;
15593         failedButOk += other.failedButOk;
15594         return *this;
15595     }
15596
15597     std::size_t Counts::total() const { return passed + failed + failedButOk; }
15598     bool Counts::allPassed() const { return failed == 0 && failedButOk == 0; }
15599     bool Counts::allOk() const { return failed == 0; }
15600
15601     Totals Totals::operator-(Totals const& other) const {
15602         Totals diff;
15603         diff.assertions = assertions - other.assertions;
15604         diff.testCases = testCases - other.testCases;
15605         return diff;
15606     }
15607
15608     Totals& Totals::operator+=(Totals const& other) {
15609         assertions += other.assertions;
15610         testCases += other.testCases;
15611         return *this;
15612     }
15613
15614     Totals Totals::delta(Totals const& prevTotals) const {
15615         Totals diff = *this - prevTotals;
15616         if (diff.assertions.failed > 0)
15617             ++diff.testCases.failed;
15618         else if (diff.assertions.failedButOk > 0)
15619             ++diff.testCases.failedButOk;
15620         else
15621             ++diff.testCases.passed;
15622         return diff;
15623     }
15624
15625 } // namespace Catch
15626 // end catch_totals.cpp
15627 // start catch_uncaught_exceptions.cpp
15628
15629 // start catch_config_uncaught_exceptions.hpp
15630
15631 //              Copyright Catch2 Authors
15632 // Distributed under the Boost Software License, Version 1.0.
15633 //   (See accompanying file LICENSE_1_0.txt or copy at
15634 //        https://www.boost.org/LICENSE_1_0.txt)
15635
15636 // SPDX-License-Identifier: BSL-1.0
15637
15638 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15639 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15640
15641 #if defined(_MSC_VER)
15642 #if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15643 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15644 #endif
15645 #endif
15646
15647 #include <exception>
15648
15649 #if defined(__cpp_lib_uncaught_exceptions) &&                                                      \
15650     !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15651
15652 #define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15653 #endif // __cpp_lib_uncaught_exceptions
15654
15655 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) &&                                    \
15656     !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) &&                                         \
15657     !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15658
15659 #define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15660 #endif
15661
15662 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15663 // end catch_config_uncaught_exceptions.hpp
15664 #include <exception>
15665
15666 namespace Catch {
15667     bool uncaught_exceptions() {
15668 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15669         return false;
15670 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15671         return std::uncaught_exceptions() > 0;
15672 #else
15673         return std::uncaught_exception();
15674 #endif
15675     }
15676 } // end namespace Catch
15677 // end catch_uncaught_exceptions.cpp
15678 // start catch_version.cpp
15679
15680 #include <ostream>
15681
15682 namespace Catch {
15683
15684     Version::Version(unsigned int _majorVersion,
15685                      unsigned int _minorVersion,
15686                      unsigned int _patchNumber,
15687                      char const* const _branchName,
15688                      unsigned int _buildNumber) :
15689         majorVersion(_majorVersion),
15690         minorVersion(_minorVersion),
15691         patchNumber(_patchNumber),
15692         branchName(_branchName),
15693         buildNumber(_buildNumber) {}
15694
15695     std::ostream& operator<<(std::ostream& os, Version const& version) {
15696         os << version.majorVersion << '.' << version.minorVersion << '.' << version.patchNumber;
15697         // branchName is never null -> 0th char is \0 if it is empty
15698         if (version.branchName[0]) {
15699             os << '-' << version.branchName << '.' << version.buildNumber;
15700         }
15701         return os;
15702     }
15703
15704     Version const& libraryVersion() {
15705         static Version version(2, 13, 7, "", 0);
15706         return version;
15707     }
15708
15709 } // namespace Catch
15710 // end catch_version.cpp
15711 // start catch_wildcard_pattern.cpp
15712
15713 namespace Catch {
15714
15715     WildcardPattern::WildcardPattern(std::string const& pattern,
15716                                      CaseSensitive::Choice caseSensitivity) :
15717         m_caseSensitivity(caseSensitivity), m_pattern(normaliseString(pattern)) {
15718         if (startsWith(m_pattern, '*')) {
15719             m_pattern = m_pattern.substr(1);
15720             m_wildcard = WildcardAtStart;
15721         }
15722         if (endsWith(m_pattern, '*')) {
15723             m_pattern = m_pattern.substr(0, m_pattern.size() - 1);
15724             m_wildcard = static_cast<WildcardPosition>(m_wildcard | WildcardAtEnd);
15725         }
15726     }
15727
15728     bool WildcardPattern::matches(std::string const& str) const {
15729         switch (m_wildcard) {
15730             case NoWildcard:
15731                 return m_pattern == normaliseString(str);
15732             case WildcardAtStart:
15733                 return endsWith(normaliseString(str), m_pattern);
15734             case WildcardAtEnd:
15735                 return startsWith(normaliseString(str), m_pattern);
15736             case WildcardAtBothEnds:
15737                 return contains(normaliseString(str), m_pattern);
15738             default:
15739                 CATCH_INTERNAL_ERROR("Unknown enum");
15740         }
15741     }
15742
15743     std::string WildcardPattern::normaliseString(std::string const& str) const {
15744         return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) : str);
15745     }
15746 } // namespace Catch
15747 // end catch_wildcard_pattern.cpp
15748 // start catch_xmlwriter.cpp
15749
15750 #include <iomanip>
15751 #include <type_traits>
15752
15753 namespace Catch {
15754
15755     namespace {
15756
15757         size_t trailingBytes(unsigned char c) {
15758             if ((c & 0xE0) == 0xC0) {
15759                 return 2;
15760             }
15761             if ((c & 0xF0) == 0xE0) {
15762                 return 3;
15763             }
15764             if ((c & 0xF8) == 0xF0) {
15765                 return 4;
15766             }
15767             CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15768         }
15769
15770         uint32_t headerValue(unsigned char c) {
15771             if ((c & 0xE0) == 0xC0) {
15772                 return c & 0x1F;
15773             }
15774             if ((c & 0xF0) == 0xE0) {
15775                 return c & 0x0F;
15776             }
15777             if ((c & 0xF8) == 0xF0) {
15778                 return c & 0x07;
15779             }
15780             CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15781         }
15782
15783         void hexEscapeChar(std::ostream& os, unsigned char c) {
15784             std::ios_base::fmtflags f(os.flags());
15785             os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15786                << static_cast<int>(c);
15787             os.flags(f);
15788         }
15789
15790         bool shouldNewline(XmlFormatting fmt) {
15791             return !!(static_cast<std::underlying_type<XmlFormatting>::type>(
15792                 fmt & XmlFormatting::Newline));
15793         }
15794
15795         bool shouldIndent(XmlFormatting fmt) {
15796             return !!(static_cast<std::underlying_type<XmlFormatting>::type>(
15797                 fmt & XmlFormatting::Indent));
15798         }
15799
15800     } // anonymous namespace
15801
15802     XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs) {
15803         return static_cast<XmlFormatting>(
15804             static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15805             static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15806     }
15807
15808     XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs) {
15809         return static_cast<XmlFormatting>(
15810             static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15811             static_cast<std::underlying_type<XmlFormatting>::type>(rhs));
15812     }
15813
15814     XmlEncode::XmlEncode(std::string const& str, ForWhat forWhat) :
15815         m_str(str), m_forWhat(forWhat) {}
15816
15817     void XmlEncode::encodeTo(std::ostream& os) const {
15818         // Apostrophe escaping not necessary if we always use " to write
15819         // attributes (see: http://www.w3.org/TR/xml/#syntax)
15820
15821         for (std::size_t idx = 0; idx < m_str.size(); ++idx) {
15822             unsigned char c = m_str[idx];
15823             switch (c) {
15824                 case '<':
15825                     os << "&lt;";
15826                     break;
15827                 case '&':
15828                     os << "&amp;";
15829                     break;
15830
15831                 case '>':
15832                     // See: http://www.w3.org/TR/xml/#syntax
15833                     if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15834                         os << "&gt;";
15835                     else
15836                         os << c;
15837                     break;
15838
15839                 case '\"':
15840                     if (m_forWhat == ForAttributes)
15841                         os << "&quot;";
15842                     else
15843                         os << c;
15844                     break;
15845
15846                 default:
15847                     // Check for control characters and invalid utf-8
15848
15849                     // Escape control characters in standard ascii
15850                     // see
15851                     // http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15852                     if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15853                         hexEscapeChar(os, c);
15854                         break;
15855                     }
15856
15857                     // Plain ASCII: Write it to stream
15858                     if (c < 0x7F) {
15859                         os << c;
15860                         break;
15861                     }
15862
15863                     // UTF-8 territory
15864                     // Check if the encoding is valid and if it is not, hex
15865                     // escape bytes. Important: We do not check the exact
15866                     // decoded values for validity, only the encoding format
15867                     // First check that this bytes is a valid lead byte:
15868                     // This means that it is not encoded as 1111 1XXX
15869                     // Or as 10XX XXXX
15870                     if (c < 0xC0 || c >= 0xF8) {
15871                         hexEscapeChar(os, c);
15872                         break;
15873                     }
15874
15875                     auto encBytes = trailingBytes(c);
15876                     // Are there enough bytes left to avoid accessing
15877                     // out-of-bounds memory?
15878                     if (idx + encBytes - 1 >= m_str.size()) {
15879                         hexEscapeChar(os, c);
15880                         break;
15881                     }
15882                     // The header is valid, check data
15883                     // The next encBytes bytes must together be a valid utf-8
15884                     // This means: bitpattern 10XX XXXX and the extracted value
15885                     // is sane (ish)
15886                     bool valid = true;
15887                     uint32_t value = headerValue(c);
15888                     for (std::size_t n = 1; n < encBytes; ++n) {
15889                         unsigned char nc = m_str[idx + n];
15890                         valid &= ((nc & 0xC0) == 0x80);
15891                         value = (value << 6) | (nc & 0x3F);
15892                     }
15893
15894                     if (
15895                         // Wrong bit pattern of following bytes
15896                         (!valid) ||
15897                         // Overlong encodings
15898                         (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) ||
15899                         (0x800 < value && value < 0x10000 && encBytes > 3) ||
15900                         // Encoded value out of range
15901                         (value >= 0x110000))
15902                     {
15903                         hexEscapeChar(os, c);
15904                         break;
15905                     }
15906
15907                     // If we got here, this is in fact a valid(ish) utf-8
15908                     // sequence
15909                     for (std::size_t n = 0; n < encBytes; ++n) {
15910                         os << m_str[idx + n];
15911                     }
15912                     idx += encBytes - 1;
15913                     break;
15914             }
15915         }
15916     }
15917
15918     std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode) {
15919         xmlEncode.encodeTo(os);
15920         return os;
15921     }
15922
15923     XmlWriter::ScopedElement::ScopedElement(XmlWriter* writer, XmlFormatting fmt) :
15924         m_writer(writer), m_fmt(fmt) {}
15925
15926     XmlWriter::ScopedElement::ScopedElement(ScopedElement&& other) noexcept :
15927         m_writer(other.m_writer), m_fmt(other.m_fmt) {
15928         other.m_writer = nullptr;
15929         other.m_fmt = XmlFormatting::None;
15930     }
15931     XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=(ScopedElement&& other) noexcept {
15932         if (m_writer) {
15933             m_writer->endElement();
15934         }
15935         m_writer = other.m_writer;
15936         other.m_writer = nullptr;
15937         m_fmt = other.m_fmt;
15938         other.m_fmt = XmlFormatting::None;
15939         return *this;
15940     }
15941
15942     XmlWriter::ScopedElement::~ScopedElement() {
15943         if (m_writer) {
15944             m_writer->endElement(m_fmt);
15945         }
15946     }
15947
15948     XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText(std::string const& text,
15949                                                                   XmlFormatting fmt) {
15950         m_writer->writeText(text, fmt);
15951         return *this;
15952     }
15953
15954     XmlWriter::XmlWriter(std::ostream& os) : m_os(os) { writeDeclaration(); }
15955
15956     XmlWriter::~XmlWriter() {
15957         while (!m_tags.empty()) {
15958             endElement();
15959         }
15960         newlineIfNecessary();
15961     }
15962
15963     XmlWriter& XmlWriter::startElement(std::string const& name, XmlFormatting fmt) {
15964         ensureTagClosed();
15965         newlineIfNecessary();
15966         if (shouldIndent(fmt)) {
15967             m_os << m_indent;
15968             m_indent += "  ";
15969         }
15970         m_os << '<' << name;
15971         m_tags.push_back(name);
15972         m_tagIsOpen = true;
15973         applyFormatting(fmt);
15974         return *this;
15975     }
15976
15977     XmlWriter::ScopedElement XmlWriter::scopedElement(std::string const& name, XmlFormatting fmt) {
15978         ScopedElement scoped(this, fmt);
15979         startElement(name, fmt);
15980         return scoped;
15981     }
15982
15983     XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15984         m_indent = m_indent.substr(0, m_indent.size() - 2);
15985
15986         if (m_tagIsOpen) {
15987             m_os << "/>";
15988             m_tagIsOpen = false;
15989         } else {
15990             newlineIfNecessary();
15991             if (shouldIndent(fmt)) {
15992                 m_os << m_indent;
15993             }
15994             m_os << "</" << m_tags.back() << ">";
15995         }
15996         m_os << std::flush;
15997         applyFormatting(fmt);
15998         m_tags.pop_back();
15999         return *this;
16000     }
16001
16002     XmlWriter& XmlWriter::writeAttribute(std::string const& name, std::string const& attribute) {
16003         if (!name.empty() && !attribute.empty())
16004             m_os << ' ' << name << "=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) << '"';
16005         return *this;
16006     }
16007
16008     XmlWriter& XmlWriter::writeAttribute(std::string const& name, bool attribute) {
16009         m_os << ' ' << name << "=\"" << (attribute ? "true" : "false") << '"';
16010         return *this;
16011     }
16012
16013     XmlWriter& XmlWriter::writeText(std::string const& text, XmlFormatting fmt) {
16014         if (!text.empty()) {
16015             bool tagWasOpen = m_tagIsOpen;
16016             ensureTagClosed();
16017             if (tagWasOpen && shouldIndent(fmt)) {
16018                 m_os << m_indent;
16019             }
16020             m_os << XmlEncode(text);
16021             applyFormatting(fmt);
16022         }
16023         return *this;
16024     }
16025
16026     XmlWriter& XmlWriter::writeComment(std::string const& text, XmlFormatting fmt) {
16027         ensureTagClosed();
16028         if (shouldIndent(fmt)) {
16029             m_os << m_indent;
16030         }
16031         m_os << "<!--" << text << "-->";
16032         applyFormatting(fmt);
16033         return *this;
16034     }
16035
16036     void XmlWriter::writeStylesheetRef(std::string const& url) {
16037         m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
16038     }
16039
16040     XmlWriter& XmlWriter::writeBlankLine() {
16041         ensureTagClosed();
16042         m_os << '\n';
16043         return *this;
16044     }
16045
16046     void XmlWriter::ensureTagClosed() {
16047         if (m_tagIsOpen) {
16048             m_os << '>' << std::flush;
16049             newlineIfNecessary();
16050             m_tagIsOpen = false;
16051         }
16052     }
16053
16054     void XmlWriter::applyFormatting(XmlFormatting fmt) { m_needsNewline = shouldNewline(fmt); }
16055
16056     void XmlWriter::writeDeclaration() { m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; }
16057
16058     void XmlWriter::newlineIfNecessary() {
16059         if (m_needsNewline) {
16060             m_os << std::endl;
16061             m_needsNewline = false;
16062         }
16063     }
16064 } // namespace Catch
16065 // end catch_xmlwriter.cpp
16066 // start catch_reporter_bases.cpp
16067
16068 #include <cstring>
16069 #include <cfloat>
16070 #include <cstdio>
16071 #include <cassert>
16072 #include <memory>
16073
16074 namespace Catch {
16075     void prepareExpandedExpression(AssertionResult& result) { result.getExpandedExpression(); }
16076
16077     // Because formatting using c++ streams is stateful, drop down to C is
16078     // required Alternatively we could use stringstream, but its performance
16079     // is... not good.
16080     std::string getFormattedDuration(double duration) {
16081         // Max exponent + 1 is required to represent the whole part
16082         // + 1 for decimal point
16083         // + 3 for the 3 decimal places
16084         // + 1 for null terminator
16085         const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
16086         char buffer[maxDoubleSize];
16087
16088         // Save previous errno, to prevent sprintf from overwriting it
16089         ErrnoGuard guard;
16090 #ifdef _MSC_VER
16091         sprintf_s(buffer, "%.3f", duration);
16092 #else
16093         std::sprintf(buffer, "%.3f", duration);
16094 #endif
16095         return std::string(buffer);
16096     }
16097
16098     bool shouldShowDuration(IConfig const& config, double duration) {
16099         if (config.showDurations() == ShowDurations::Always) {
16100             return true;
16101         }
16102         if (config.showDurations() == ShowDurations::Never) {
16103             return false;
16104         }
16105         const double min = config.minDuration();
16106         return min >= 0 && duration >= min;
16107     }
16108
16109     std::string serializeFilters(std::vector<std::string> const& container) {
16110         ReusableStringStream oss;
16111         bool first = true;
16112         for (auto&& filter : container) {
16113             if (!first)
16114                 oss << ' ';
16115             else
16116                 first = false;
16117
16118             oss << filter;
16119         }
16120         return oss.str();
16121     }
16122
16123     TestEventListenerBase::TestEventListenerBase(ReporterConfig const& _config) :
16124         StreamingReporterBase(_config) {}
16125
16126     std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
16127         return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High};
16128     }
16129
16130     void TestEventListenerBase::assertionStarting(AssertionInfo const&) {}
16131
16132     bool TestEventListenerBase::assertionEnded(AssertionStats const&) { return false; }
16133
16134 } // end namespace Catch
16135 // end catch_reporter_bases.cpp
16136 // start catch_reporter_compact.cpp
16137
16138 namespace {
16139
16140 #ifdef CATCH_PLATFORM_MAC
16141     const char* failedString() { return "FAILED"; }
16142     const char* passedString() { return "PASSED"; }
16143 #else
16144     const char* failedString() { return "failed"; }
16145     const char* passedString() { return "passed"; }
16146 #endif
16147
16148     // Colour::LightGrey
16149     Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
16150
16151     std::string bothOrAll(std::size_t count) {
16152         return count == 1 ? std::string() : count == 2 ? "both " : "all ";
16153     }
16154
16155 } // namespace
16156
16157 namespace Catch {
16158     namespace {
16159         // Colour, message variants:
16160         // - white: No tests ran.
16161         // -   red: Failed [both/all] N test cases, failed [both/all] M
16162         // assertions.
16163         // - white: Passed [both/all] N test cases (no assertions).
16164         // -   red: Failed N tests cases, failed M assertions.
16165         // - green: Passed [both/all] N tests cases with M assertions.
16166         void printTotals(std::ostream& out, const Totals& totals) {
16167             if (totals.testCases.total() == 0) {
16168                 out << "No tests ran.";
16169             } else if (totals.testCases.failed == totals.testCases.total()) {
16170                 Colour colour(Colour::ResultError);
16171                 const std::string qualify_assertions_failed =
16172                     totals.assertions.failed == totals.assertions.total()
16173                         ? bothOrAll(totals.assertions.failed)
16174                         : std::string();
16175                 out << "Failed " << bothOrAll(totals.testCases.failed)
16176                     << pluralise(totals.testCases.failed, "test case")
16177                     << ", "
16178                        "failed "
16179                     << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion")
16180                     << '.';
16181             } else if (totals.assertions.total() == 0) {
16182                 out << "Passed " << bothOrAll(totals.testCases.total())
16183                     << pluralise(totals.testCases.total(), "test case") << " (no assertions).";
16184             } else if (totals.assertions.failed) {
16185                 Colour colour(Colour::ResultError);
16186                 out << "Failed " << pluralise(totals.testCases.failed, "test case")
16187                     << ", "
16188                        "failed "
16189                     << pluralise(totals.assertions.failed, "assertion") << '.';
16190             } else {
16191                 Colour colour(Colour::ResultSuccess);
16192                 out << "Passed " << bothOrAll(totals.testCases.passed)
16193                     << pluralise(totals.testCases.passed, "test case") << " with "
16194                     << pluralise(totals.assertions.passed, "assertion") << '.';
16195             }
16196         }
16197
16198         // Implementation of CompactReporter formatting
16199         class AssertionPrinter {
16200         public:
16201             AssertionPrinter& operator=(AssertionPrinter const&) = delete;
16202             AssertionPrinter(AssertionPrinter const&) = delete;
16203             AssertionPrinter(std::ostream& _stream,
16204                              AssertionStats const& _stats,
16205                              bool _printInfoMessages) :
16206                 stream(_stream),
16207                 result(_stats.assertionResult),
16208                 messages(_stats.infoMessages),
16209                 itMessage(_stats.infoMessages.begin()),
16210                 printInfoMessages(_printInfoMessages) {}
16211
16212             void print() {
16213                 printSourceInfo();
16214
16215                 itMessage = messages.begin();
16216
16217                 switch (result.getResultType()) {
16218                     case ResultWas::Ok:
16219                         printResultType(Colour::ResultSuccess, passedString());
16220                         printOriginalExpression();
16221                         printReconstructedExpression();
16222                         if (!result.hasExpression())
16223                             printRemainingMessages(Colour::None);
16224                         else
16225                             printRemainingMessages();
16226                         break;
16227                     case ResultWas::ExpressionFailed:
16228                         if (result.isOk())
16229                             printResultType(Colour::ResultSuccess,
16230                                             failedString() + std::string(" - but was ok"));
16231                         else
16232                             printResultType(Colour::Error, failedString());
16233                         printOriginalExpression();
16234                         printReconstructedExpression();
16235                         printRemainingMessages();
16236                         break;
16237                     case ResultWas::ThrewException:
16238                         printResultType(Colour::Error, failedString());
16239                         printIssue("unexpected exception with message:");
16240                         printMessage();
16241                         printExpressionWas();
16242                         printRemainingMessages();
16243                         break;
16244                     case ResultWas::FatalErrorCondition:
16245                         printResultType(Colour::Error, failedString());
16246                         printIssue("fatal error condition with message:");
16247                         printMessage();
16248                         printExpressionWas();
16249                         printRemainingMessages();
16250                         break;
16251                     case ResultWas::DidntThrowException:
16252                         printResultType(Colour::Error, failedString());
16253                         printIssue("expected exception, got none");
16254                         printExpressionWas();
16255                         printRemainingMessages();
16256                         break;
16257                     case ResultWas::Info:
16258                         printResultType(Colour::None, "info");
16259                         printMessage();
16260                         printRemainingMessages();
16261                         break;
16262                     case ResultWas::Warning:
16263                         printResultType(Colour::None, "warning");
16264                         printMessage();
16265                         printRemainingMessages();
16266                         break;
16267                     case ResultWas::ExplicitFailure:
16268                         printResultType(Colour::Error, failedString());
16269                         printIssue("explicitly");
16270                         printRemainingMessages(Colour::None);
16271                         break;
16272                         // These cases are here to prevent compiler warnings
16273                     case ResultWas::Unknown:
16274                     case ResultWas::FailureBit:
16275                     case ResultWas::Exception:
16276                         printResultType(Colour::Error, "** internal error **");
16277                         break;
16278                 }
16279             }
16280
16281         private:
16282             void printSourceInfo() const {
16283                 Colour colourGuard(Colour::FileName);
16284                 stream << result.getSourceInfo() << ':';
16285             }
16286
16287             void printResultType(Colour::Code colour, std::string const& passOrFail) const {
16288                 if (!passOrFail.empty()) {
16289                     {
16290                         Colour colourGuard(colour);
16291                         stream << ' ' << passOrFail;
16292                     }
16293                     stream << ':';
16294                 }
16295             }
16296
16297             void printIssue(std::string const& issue) const { stream << ' ' << issue; }
16298
16299             void printExpressionWas() {
16300                 if (result.hasExpression()) {
16301                     stream << ';';
16302                     {
16303                         Colour colour(dimColour());
16304                         stream << " expression was:";
16305                     }
16306                     printOriginalExpression();
16307                 }
16308             }
16309
16310             void printOriginalExpression() const {
16311                 if (result.hasExpression()) {
16312                     stream << ' ' << result.getExpression();
16313                 }
16314             }
16315
16316             void printReconstructedExpression() const {
16317                 if (result.hasExpandedExpression()) {
16318                     {
16319                         Colour colour(dimColour());
16320                         stream << " for: ";
16321                     }
16322                     stream << result.getExpandedExpression();
16323                 }
16324             }
16325
16326             void printMessage() {
16327                 if (itMessage != messages.end()) {
16328                     stream << " '" << itMessage->message << '\'';
16329                     ++itMessage;
16330                 }
16331             }
16332
16333             void printRemainingMessages(Colour::Code colour = dimColour()) {
16334                 if (itMessage == messages.end())
16335                     return;
16336
16337                 const auto itEnd = messages.cend();
16338                 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16339
16340                 {
16341                     Colour colourGuard(colour);
16342                     stream << " with " << pluralise(N, "message") << ':';
16343                 }
16344
16345                 while (itMessage != itEnd) {
16346                     // If this assertion is a warning ignore any INFO messages
16347                     if (printInfoMessages || itMessage->type != ResultWas::Info) {
16348                         printMessage();
16349                         if (itMessage != itEnd) {
16350                             Colour colourGuard(dimColour());
16351                             stream << " and";
16352                         }
16353                         continue;
16354                     }
16355                     ++itMessage;
16356                 }
16357             }
16358
16359         private:
16360             std::ostream& stream;
16361             AssertionResult const& result;
16362             std::vector<MessageInfo> messages;
16363             std::vector<MessageInfo>::const_iterator itMessage;
16364             bool printInfoMessages;
16365         };
16366
16367     } // namespace
16368
16369     std::string CompactReporter::getDescription() {
16370         return "Reports test results on a single line, suitable for IDEs";
16371     }
16372
16373     void CompactReporter::noMatchingTestCases(std::string const& spec) {
16374         stream << "No test cases matched '" << spec << '\'' << std::endl;
16375     }
16376
16377     void CompactReporter::assertionStarting(AssertionInfo const&) {}
16378
16379     bool CompactReporter::assertionEnded(AssertionStats const& _assertionStats) {
16380         AssertionResult const& result = _assertionStats.assertionResult;
16381
16382         bool printInfoMessages = true;
16383
16384         // Drop out if result was successful and we're not printing those
16385         if (!m_config->includeSuccessfulResults() && result.isOk()) {
16386             if (result.getResultType() != ResultWas::Warning)
16387                 return false;
16388             printInfoMessages = false;
16389         }
16390
16391         AssertionPrinter printer(stream, _assertionStats, printInfoMessages);
16392         printer.print();
16393
16394         stream << std::endl;
16395         return true;
16396     }
16397
16398     void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16399         double dur = _sectionStats.durationInSeconds;
16400         if (shouldShowDuration(*m_config, dur)) {
16401             stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16402                    << std::endl;
16403         }
16404     }
16405
16406     void CompactReporter::testRunEnded(TestRunStats const& _testRunStats) {
16407         printTotals(stream, _testRunStats.totals);
16408         stream << '\n' << std::endl;
16409         StreamingReporterBase::testRunEnded(_testRunStats);
16410     }
16411
16412     CompactReporter::~CompactReporter() {}
16413
16414     CATCH_REGISTER_REPORTER("compact", CompactReporter)
16415
16416 } // end namespace Catch
16417 // end catch_reporter_compact.cpp
16418 // start catch_reporter_console.cpp
16419
16420 #include <cfloat>
16421 #include <cstdio>
16422
16423 #if defined(_MSC_VER)
16424 #pragma warning(push)
16425 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in switch
16426   // Note that 4062 (not all labels are handled and default is missing) is
16427   // enabled
16428 #endif
16429
16430 #if defined(__clang__)
16431 #pragma clang diagnostic push
16432 // For simplicity, benchmarking-only helpers are always enabled
16433 #pragma clang diagnostic ignored "-Wunused-function"
16434 #endif
16435
16436 namespace Catch {
16437
16438     namespace {
16439
16440         // Formatter impl for ConsoleReporter
16441         class ConsoleAssertionPrinter {
16442         public:
16443             ConsoleAssertionPrinter& operator=(ConsoleAssertionPrinter const&) = delete;
16444             ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16445             ConsoleAssertionPrinter(std::ostream& _stream,
16446                                     AssertionStats const& _stats,
16447                                     bool _printInfoMessages) :
16448                 stream(_stream),
16449                 stats(_stats),
16450                 result(_stats.assertionResult),
16451                 colour(Colour::None),
16452                 message(result.getMessage()),
16453                 messages(_stats.infoMessages),
16454                 printInfoMessages(_printInfoMessages) {
16455                 switch (result.getResultType()) {
16456                     case ResultWas::Ok:
16457                         colour = Colour::Success;
16458                         passOrFail = "PASSED";
16459                         // if( result.hasMessage() )
16460                         if (_stats.infoMessages.size() == 1)
16461                             messageLabel = "with message";
16462                         if (_stats.infoMessages.size() > 1)
16463                             messageLabel = "with messages";
16464                         break;
16465                     case ResultWas::ExpressionFailed:
16466                         if (result.isOk()) {
16467                             colour = Colour::Success;
16468                             passOrFail = "FAILED - but was ok";
16469                         } else {
16470                             colour = Colour::Error;
16471                             passOrFail = "FAILED";
16472                         }
16473                         if (_stats.infoMessages.size() == 1)
16474                             messageLabel = "with message";
16475                         if (_stats.infoMessages.size() > 1)
16476                             messageLabel = "with messages";
16477                         break;
16478                     case ResultWas::ThrewException:
16479                         colour = Colour::Error;
16480                         passOrFail = "FAILED";
16481                         messageLabel = "due to unexpected exception with ";
16482                         if (_stats.infoMessages.size() == 1)
16483                             messageLabel += "message";
16484                         if (_stats.infoMessages.size() > 1)
16485                             messageLabel += "messages";
16486                         break;
16487                     case ResultWas::FatalErrorCondition:
16488                         colour = Colour::Error;
16489                         passOrFail = "FAILED";
16490                         messageLabel = "due to a fatal error condition";
16491                         break;
16492                     case ResultWas::DidntThrowException:
16493                         colour = Colour::Error;
16494                         passOrFail = "FAILED";
16495                         messageLabel = "because no exception was thrown where "
16496                                        "one was expected";
16497                         break;
16498                     case ResultWas::Info:
16499                         messageLabel = "info";
16500                         break;
16501                     case ResultWas::Warning:
16502                         messageLabel = "warning";
16503                         break;
16504                     case ResultWas::ExplicitFailure:
16505                         passOrFail = "FAILED";
16506                         colour = Colour::Error;
16507                         if (_stats.infoMessages.size() == 1)
16508                             messageLabel = "explicitly with message";
16509                         if (_stats.infoMessages.size() > 1)
16510                             messageLabel = "explicitly with messages";
16511                         break;
16512                         // These cases are here to prevent compiler warnings
16513                     case ResultWas::Unknown:
16514                     case ResultWas::FailureBit:
16515                     case ResultWas::Exception:
16516                         passOrFail = "** internal error **";
16517                         colour = Colour::Error;
16518                         break;
16519                 }
16520             }
16521
16522             void print() const {
16523                 printSourceInfo();
16524                 if (stats.totals.assertions.total() > 0) {
16525                     printResultType();
16526                     printOriginalExpression();
16527                     printReconstructedExpression();
16528                 } else {
16529                     stream << '\n';
16530                 }
16531                 printMessage();
16532             }
16533
16534         private:
16535             void printResultType() const {
16536                 if (!passOrFail.empty()) {
16537                     Colour colourGuard(colour);
16538                     stream << passOrFail << ":\n";
16539                 }
16540             }
16541             void printOriginalExpression() const {
16542                 if (result.hasExpression()) {
16543                     Colour colourGuard(Colour::OriginalExpression);
16544                     stream << "  ";
16545                     stream << result.getExpressionInMacro();
16546                     stream << '\n';
16547                 }
16548             }
16549             void printReconstructedExpression() const {
16550                 if (result.hasExpandedExpression()) {
16551                     stream << "with expansion:\n";
16552                     Colour colourGuard(Colour::ReconstructedExpression);
16553                     stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16554                 }
16555             }
16556             void printMessage() const {
16557                 if (!messageLabel.empty())
16558                     stream << messageLabel << ':' << '\n';
16559                 for (auto const& msg : messages) {
16560                     // If this assertion is a warning ignore any INFO messages
16561                     if (printInfoMessages || msg.type != ResultWas::Info)
16562                         stream << Column(msg.message).indent(2) << '\n';
16563                 }
16564             }
16565             void printSourceInfo() const {
16566                 Colour colourGuard(Colour::FileName);
16567                 stream << result.getSourceInfo() << ": ";
16568             }
16569
16570             std::ostream& stream;
16571             AssertionStats const& stats;
16572             AssertionResult const& result;
16573             Colour::Code colour;
16574             std::string passOrFail;
16575             std::string messageLabel;
16576             std::string message;
16577             std::vector<MessageInfo> messages;
16578             bool printInfoMessages;
16579         };
16580
16581         std::size_t makeRatio(std::size_t number, std::size_t total) {
16582             std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16583             return (ratio == 0 && number > 0) ? 1 : ratio;
16584         }
16585
16586         std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16587             if (i > j && i > k)
16588                 return i;
16589             else if (j > k)
16590                 return j;
16591             else
16592                 return k;
16593         }
16594
16595         struct ColumnInfo {
16596             enum Justification { Left, Right };
16597             std::string name;
16598             int width;
16599             Justification justification;
16600         };
16601         struct ColumnBreak {};
16602         struct RowBreak {};
16603
16604         class Duration {
16605             enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes };
16606             static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16607             static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16608             static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16609             static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16610
16611             double m_inNanoseconds;
16612             Unit m_units;
16613
16614         public:
16615             explicit Duration(double inNanoseconds, Unit units = Unit::Auto) :
16616                 m_inNanoseconds(inNanoseconds), m_units(units) {
16617                 if (m_units == Unit::Auto) {
16618                     if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16619                         m_units = Unit::Nanoseconds;
16620                     else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16621                         m_units = Unit::Microseconds;
16622                     else if (m_inNanoseconds < s_nanosecondsInASecond)
16623                         m_units = Unit::Milliseconds;
16624                     else if (m_inNanoseconds < s_nanosecondsInAMinute)
16625                         m_units = Unit::Seconds;
16626                     else
16627                         m_units = Unit::Minutes;
16628                 }
16629             }
16630
16631             auto value() const -> double {
16632                 switch (m_units) {
16633                     case Unit::Microseconds:
16634                         return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16635                     case Unit::Milliseconds:
16636                         return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16637                     case Unit::Seconds:
16638                         return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16639                     case Unit::Minutes:
16640                         return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16641                     default:
16642                         return m_inNanoseconds;
16643                 }
16644             }
16645             auto unitsAsString() const -> std::string {
16646                 switch (m_units) {
16647                     case Unit::Nanoseconds:
16648                         return "ns";
16649                     case Unit::Microseconds:
16650                         return "us";
16651                     case Unit::Milliseconds:
16652                         return "ms";
16653                     case Unit::Seconds:
16654                         return "s";
16655                     case Unit::Minutes:
16656                         return "m";
16657                     default:
16658                         return "** internal error **";
16659                 }
16660             }
16661             friend auto operator<<(std::ostream& os, Duration const& duration) -> std::ostream& {
16662                 return os << duration.value() << ' ' << duration.unitsAsString();
16663             }
16664         };
16665     } // namespace
16666
16667     class TablePrinter {
16668         std::ostream& m_os;
16669         std::vector<ColumnInfo> m_columnInfos;
16670         std::ostringstream m_oss;
16671         int m_currentColumn = -1;
16672         bool m_isOpen = false;
16673
16674     public:
16675         TablePrinter(std::ostream& os, std::vector<ColumnInfo> columnInfos) :
16676             m_os(os), m_columnInfos(std::move(columnInfos)) {}
16677
16678         auto columnInfos() const -> std::vector<ColumnInfo> const& { return m_columnInfos; }
16679
16680         void open() {
16681             if (!m_isOpen) {
16682                 m_isOpen = true;
16683                 *this << RowBreak();
16684
16685                 Columns headerCols;
16686                 Spacer spacer(2);
16687                 for (auto const& info : m_columnInfos) {
16688                     headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16689                     headerCols += spacer;
16690                 }
16691                 m_os << headerCols << '\n';
16692
16693                 m_os << Catch::getLineOfChars<'-'>() << '\n';
16694             }
16695         }
16696         void close() {
16697             if (m_isOpen) {
16698                 *this << RowBreak();
16699                 m_os << std::endl;
16700                 m_isOpen = false;
16701             }
16702         }
16703
16704         template <typename T> friend TablePrinter& operator<<(TablePrinter& tp, T const& value) {
16705             tp.m_oss << value;
16706             return tp;
16707         }
16708
16709         friend TablePrinter& operator<<(TablePrinter& tp, ColumnBreak) {
16710             auto colStr = tp.m_oss.str();
16711             const auto strSize = colStr.size();
16712             tp.m_oss.str("");
16713             tp.open();
16714             if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16715                 tp.m_currentColumn = -1;
16716                 tp.m_os << '\n';
16717             }
16718             tp.m_currentColumn++;
16719
16720             auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16721             auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16722                                ? std::string(colInfo.width - (strSize + 1), ' ')
16723                                : std::string();
16724             if (colInfo.justification == ColumnInfo::Left)
16725                 tp.m_os << colStr << padding << ' ';
16726             else
16727                 tp.m_os << padding << colStr << ' ';
16728             return tp;
16729         }
16730
16731         friend TablePrinter& operator<<(TablePrinter& tp, RowBreak) {
16732             if (tp.m_currentColumn > 0) {
16733                 tp.m_os << '\n';
16734                 tp.m_currentColumn = -1;
16735             }
16736             return tp;
16737         }
16738     };
16739
16740     ConsoleReporter::ConsoleReporter(ReporterConfig const& config) :
16741         StreamingReporterBase(config),
16742         m_tablePrinter(new TablePrinter(config.stream(), [&config]() -> std::vector<ColumnInfo> {
16743             if (config.fullConfig()->benchmarkNoAnalysis()) {
16744                 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16745                         {"     samples", 14, ColumnInfo::Right},
16746                         {"  iterations", 14, ColumnInfo::Right},
16747                         {"        mean", 14, ColumnInfo::Right}};
16748             } else {
16749                 return {{"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16750                         {"samples      mean       std dev", 14, ColumnInfo::Right},
16751                         {"iterations   low mean   low std dev", 14, ColumnInfo::Right},
16752                         {"estimated    high mean  high std dev", 14, ColumnInfo::Right}};
16753             }
16754         }())) {}
16755     ConsoleReporter::~ConsoleReporter() = default;
16756
16757     std::string ConsoleReporter::getDescription() {
16758         return "Reports test results as plain lines of text";
16759     }
16760
16761     void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16762         stream << "No test cases matched '" << spec << '\'' << std::endl;
16763     }
16764
16765     void ConsoleReporter::reportInvalidArguments(std::string const& arg) {
16766         stream << "Invalid Filter: " << arg << std::endl;
16767     }
16768
16769     void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16770
16771     bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16772         AssertionResult const& result = _assertionStats.assertionResult;
16773
16774         bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16775
16776         // Drop out if result was successful but we're not printing them.
16777         if (!includeResults && result.getResultType() != ResultWas::Warning)
16778             return false;
16779
16780         lazyPrint();
16781
16782         ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16783         printer.print();
16784         stream << std::endl;
16785         return true;
16786     }
16787
16788     void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16789         m_tablePrinter->close();
16790         m_headerPrinted = false;
16791         StreamingReporterBase::sectionStarting(_sectionInfo);
16792     }
16793     void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16794         m_tablePrinter->close();
16795         if (_sectionStats.missingAssertions) {
16796             lazyPrint();
16797             Colour colour(Colour::ResultError);
16798             if (m_sectionStack.size() > 1)
16799                 stream << "\nNo assertions in section";
16800             else
16801                 stream << "\nNo assertions in test case";
16802             stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16803         }
16804         double dur = _sectionStats.durationInSeconds;
16805         if (shouldShowDuration(*m_config, dur)) {
16806             stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name
16807                    << std::endl;
16808         }
16809         if (m_headerPrinted) {
16810             m_headerPrinted = false;
16811         }
16812         StreamingReporterBase::sectionEnded(_sectionStats);
16813     }
16814
16815 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16816     void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16817         lazyPrintWithoutClosingBenchmarkTable();
16818
16819         auto nameCol = Column(name).width(
16820             static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16821
16822         bool firstLine = true;
16823         for (auto line : nameCol) {
16824             if (!firstLine)
16825                 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16826             else
16827                 firstLine = false;
16828
16829             (*m_tablePrinter) << line << ColumnBreak();
16830         }
16831     }
16832
16833     void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16834         (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations << ColumnBreak();
16835         if (!m_config->benchmarkNoAnalysis())
16836             (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16837     }
16838     void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16839         if (m_config->benchmarkNoAnalysis()) {
16840             (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16841         } else {
16842             (*m_tablePrinter) << ColumnBreak() << Duration(stats.mean.point.count())
16843                               << ColumnBreak() << Duration(stats.mean.lower_bound.count())
16844                               << ColumnBreak() << Duration(stats.mean.upper_bound.count())
16845                               << ColumnBreak() << ColumnBreak()
16846                               << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16847                               << Duration(stats.standardDeviation.lower_bound.count())
16848                               << ColumnBreak()
16849                               << Duration(stats.standardDeviation.upper_bound.count())
16850                               << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak()
16851                               << ColumnBreak();
16852         }
16853     }
16854
16855     void ConsoleReporter::benchmarkFailed(std::string const& error) {
16856         Colour colour(Colour::Red);
16857         (*m_tablePrinter) << "Benchmark failed (" << error << ')' << ColumnBreak() << RowBreak();
16858     }
16859 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16860
16861     void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16862         m_tablePrinter->close();
16863         StreamingReporterBase::testCaseEnded(_testCaseStats);
16864         m_headerPrinted = false;
16865     }
16866     void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16867         if (currentGroupInfo.used) {
16868             printSummaryDivider();
16869             stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16870             printTotals(_testGroupStats.totals);
16871             stream << '\n' << std::endl;
16872         }
16873         StreamingReporterBase::testGroupEnded(_testGroupStats);
16874     }
16875     void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16876         printTotalsDivider(_testRunStats.totals);
16877         printTotals(_testRunStats.totals);
16878         stream << std::endl;
16879         StreamingReporterBase::testRunEnded(_testRunStats);
16880     }
16881     void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16882         StreamingReporterBase::testRunStarting(_testInfo);
16883         printTestFilters();
16884     }
16885
16886     void ConsoleReporter::lazyPrint() {
16887
16888         m_tablePrinter->close();
16889         lazyPrintWithoutClosingBenchmarkTable();
16890     }
16891
16892     void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16893
16894         if (!currentTestRunInfo.used)
16895             lazyPrintRunInfo();
16896         if (!currentGroupInfo.used)
16897             lazyPrintGroupInfo();
16898
16899         if (!m_headerPrinted) {
16900             printTestCaseAndSectionHeader();
16901             m_headerPrinted = true;
16902         }
16903     }
16904     void ConsoleReporter::lazyPrintRunInfo() {
16905         stream << '\n' << getLineOfChars<'~'>() << '\n';
16906         Colour colour(Colour::SecondaryText);
16907         stream << currentTestRunInfo->name << " is a Catch v" << libraryVersion()
16908                << " host application.\n"
16909                << "Run with -? for options\n\n";
16910
16911         if (m_config->rngSeed() != 0)
16912             stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16913
16914         currentTestRunInfo.used = true;
16915     }
16916     void ConsoleReporter::lazyPrintGroupInfo() {
16917         if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16918             printClosedHeader("Group: " + currentGroupInfo->name);
16919             currentGroupInfo.used = true;
16920         }
16921     }
16922     void ConsoleReporter::printTestCaseAndSectionHeader() {
16923         assert(!m_sectionStack.empty());
16924         printOpenHeader(currentTestCaseInfo->name);
16925
16926         if (m_sectionStack.size() > 1) {
16927             Colour colourGuard(Colour::Headers);
16928
16929             auto it = m_sectionStack.begin() + 1, // Skip first section (test case)
16930                 itEnd = m_sectionStack.end();
16931             for (; it != itEnd; ++it)
16932                 printHeaderString(it->name, 2);
16933         }
16934
16935         SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16936
16937         stream << getLineOfChars<'-'>() << '\n';
16938         Colour colourGuard(Colour::FileName);
16939         stream << lineInfo << '\n';
16940         stream << getLineOfChars<'.'>() << '\n' << std::endl;
16941     }
16942
16943     void ConsoleReporter::printClosedHeader(std::string const& _name) {
16944         printOpenHeader(_name);
16945         stream << getLineOfChars<'.'>() << '\n';
16946     }
16947     void ConsoleReporter::printOpenHeader(std::string const& _name) {
16948         stream << getLineOfChars<'-'>() << '\n';
16949         {
16950             Colour colourGuard(Colour::Headers);
16951             printHeaderString(_name);
16952         }
16953     }
16954
16955     // if string has a : in first line will set indent to follow it on
16956     // subsequent lines
16957     void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16958         std::size_t i = _string.find(": ");
16959         if (i != std::string::npos)
16960             i += 2;
16961         else
16962             i = 0;
16963         stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16964     }
16965
16966     struct SummaryColumn {
16967
16968         SummaryColumn(std::string _label, Colour::Code _colour) :
16969             label(std::move(_label)), colour(_colour) {}
16970         SummaryColumn addRow(std::size_t count) {
16971             ReusableStringStream rss;
16972             rss << count;
16973             std::string row = rss.str();
16974             for (auto& oldRow : rows) {
16975                 while (oldRow.size() < row.size())
16976                     oldRow = ' ' + oldRow;
16977                 while (oldRow.size() > row.size())
16978                     row = ' ' + row;
16979             }
16980             rows.push_back(row);
16981             return *this;
16982         }
16983
16984         std::string label;
16985         Colour::Code colour;
16986         std::vector<std::string> rows;
16987     };
16988
16989     void ConsoleReporter::printTotals(Totals const& totals) {
16990         if (totals.testCases.total() == 0) {
16991             stream << Colour(Colour::Warning) << "No tests ran\n";
16992         } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16993             stream << Colour(Colour::ResultSuccess) << "All tests passed";
16994             stream << " (" << pluralise(totals.assertions.passed, "assertion") << " in "
16995                    << pluralise(totals.testCases.passed, "test case") << ')' << '\n';
16996         } else {
16997
16998             std::vector<SummaryColumn> columns;
16999             columns.push_back(SummaryColumn("", Colour::None)
17000                                   .addRow(totals.testCases.total())
17001                                   .addRow(totals.assertions.total()));
17002             columns.push_back(SummaryColumn("passed", Colour::Success)
17003                                   .addRow(totals.testCases.passed)
17004                                   .addRow(totals.assertions.passed));
17005             columns.push_back(SummaryColumn("failed", Colour::ResultError)
17006                                   .addRow(totals.testCases.failed)
17007                                   .addRow(totals.assertions.failed));
17008             columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
17009                                   .addRow(totals.testCases.failedButOk)
17010                                   .addRow(totals.assertions.failedButOk));
17011
17012             printSummaryRow("test cases", columns, 0);
17013             printSummaryRow("assertions", columns, 1);
17014         }
17015     }
17016     void ConsoleReporter::printSummaryRow(std::string const& label,
17017                                           std::vector<SummaryColumn> const& cols,
17018                                           std::size_t row) {
17019         for (auto col : cols) {
17020             std::string value = col.rows[row];
17021             if (col.label.empty()) {
17022                 stream << label << ": ";
17023                 if (value != "0")
17024                     stream << value;
17025                 else
17026                     stream << Colour(Colour::Warning) << "- none -";
17027             } else if (value != "0") {
17028                 stream << Colour(Colour::LightGrey) << " | ";
17029                 stream << Colour(col.colour) << value << ' ' << col.label;
17030             }
17031         }
17032         stream << '\n';
17033     }
17034
17035     void ConsoleReporter::printTotalsDivider(Totals const& totals) {
17036         if (totals.testCases.total() > 0) {
17037             std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
17038             std::size_t failedButOkRatio =
17039                 makeRatio(totals.testCases.failedButOk, totals.testCases.total());
17040             std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
17041             while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
17042                 findMax(failedRatio, failedButOkRatio, passedRatio)++;
17043             while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
17044                 findMax(failedRatio, failedButOkRatio, passedRatio)--;
17045
17046             stream << Colour(Colour::Error) << std::string(failedRatio, '=');
17047             stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
17048             if (totals.testCases.allPassed())
17049                 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
17050             else
17051                 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
17052         } else {
17053             stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
17054         }
17055         stream << '\n';
17056     }
17057     void ConsoleReporter::printSummaryDivider() { stream << getLineOfChars<'-'>() << '\n'; }
17058
17059     void ConsoleReporter::printTestFilters() {
17060         if (m_config->testSpec().hasFilters()) {
17061             Colour guard(Colour::BrightYellow);
17062             stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
17063         }
17064     }
17065
17066     CATCH_REGISTER_REPORTER("console", ConsoleReporter)
17067
17068 } // end namespace Catch
17069
17070 #if defined(_MSC_VER)
17071 #pragma warning(pop)
17072 #endif
17073
17074 #if defined(__clang__)
17075 #pragma clang diagnostic pop
17076 #endif
17077 // end catch_reporter_console.cpp
17078 // start catch_reporter_junit.cpp
17079
17080 #include <cassert>
17081 #include <sstream>
17082 #include <ctime>
17083 #include <algorithm>
17084 #include <iomanip>
17085
17086 namespace Catch {
17087
17088     namespace {
17089         std::string getCurrentTimestamp() {
17090             // Beware, this is not reentrant because of backward compatibility
17091             // issues Also, UTC only, again because of backward compatibility
17092             // (%z is C++11)
17093             time_t rawtime;
17094             std::time(&rawtime);
17095             auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
17096
17097 #ifdef _MSC_VER
17098             std::tm timeInfo = {};
17099             gmtime_s(&timeInfo, &rawtime);
17100 #else
17101             std::tm* timeInfo;
17102             timeInfo = std::gmtime(&rawtime);
17103 #endif
17104
17105             char timeStamp[timeStampSize];
17106             const char* const fmt = "%Y-%m-%dT%H:%M:%SZ";
17107
17108 #ifdef _MSC_VER
17109             std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
17110 #else
17111             std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
17112 #endif
17113             return std::string(timeStamp, timeStampSize - 1);
17114         }
17115
17116         std::string fileNameTag(const std::vector<std::string>& tags) {
17117             auto it = std::find_if(
17118                 begin(tags), end(tags), [](std::string const& tag) { return tag.front() == '#'; });
17119             if (it != tags.end())
17120                 return it->substr(1);
17121             return std::string();
17122         }
17123
17124         // Formats the duration in seconds to 3 decimal places.
17125         // This is done because some genius defined Maven Surefire schema
17126         // in a way that only accepts 3 decimal places, and tools like
17127         // Jenkins use that schema for validation JUnit reporter output.
17128         std::string formatDuration(double seconds) {
17129             ReusableStringStream rss;
17130             rss << std::fixed << std::setprecision(3) << seconds;
17131             return rss.str();
17132         }
17133
17134     } // anonymous namespace
17135
17136     JunitReporter::JunitReporter(ReporterConfig const& _config) :
17137         CumulativeReporterBase(_config), xml(_config.stream()) {
17138         m_reporterPrefs.shouldRedirectStdOut = true;
17139         m_reporterPrefs.shouldReportAllAssertions = true;
17140     }
17141
17142     JunitReporter::~JunitReporter() {}
17143
17144     std::string JunitReporter::getDescription() {
17145         return "Reports test results in an XML format that looks like Ant's "
17146                "junitreport target";
17147     }
17148
17149     void JunitReporter::noMatchingTestCases(std::string const& /*spec*/) {}
17150
17151     void JunitReporter::testRunStarting(TestRunInfo const& runInfo) {
17152         CumulativeReporterBase::testRunStarting(runInfo);
17153         xml.startElement("testsuites");
17154     }
17155
17156     void JunitReporter::testGroupStarting(GroupInfo const& groupInfo) {
17157         suiteTimer.start();
17158         stdOutForSuite.clear();
17159         stdErrForSuite.clear();
17160         unexpectedExceptions = 0;
17161         CumulativeReporterBase::testGroupStarting(groupInfo);
17162     }
17163
17164     void JunitReporter::testCaseStarting(TestCaseInfo const& testCaseInfo) {
17165         m_okToFail = testCaseInfo.okToFail();
17166     }
17167
17168     bool JunitReporter::assertionEnded(AssertionStats const& assertionStats) {
17169         if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException &&
17170             !m_okToFail)
17171             unexpectedExceptions++;
17172         return CumulativeReporterBase::assertionEnded(assertionStats);
17173     }
17174
17175     void JunitReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17176         stdOutForSuite += testCaseStats.stdOut;
17177         stdErrForSuite += testCaseStats.stdErr;
17178         CumulativeReporterBase::testCaseEnded(testCaseStats);
17179     }
17180
17181     void JunitReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17182         double suiteTime = suiteTimer.getElapsedSeconds();
17183         CumulativeReporterBase::testGroupEnded(testGroupStats);
17184         writeGroup(*m_testGroups.back(), suiteTime);
17185     }
17186
17187     void JunitReporter::testRunEndedCumulative() { xml.endElement(); }
17188
17189     void JunitReporter::writeGroup(TestGroupNode const& groupNode, double suiteTime) {
17190         XmlWriter::ScopedElement e = xml.scopedElement("testsuite");
17191
17192         TestGroupStats const& stats = groupNode.value;
17193         xml.writeAttribute("name", stats.groupInfo.name);
17194         xml.writeAttribute("errors", unexpectedExceptions);
17195         xml.writeAttribute("failures", stats.totals.assertions.failed - unexpectedExceptions);
17196         xml.writeAttribute("tests", stats.totals.assertions.total());
17197         xml.writeAttribute("hostname", "tbd"); // !TBD
17198         if (m_config->showDurations() == ShowDurations::Never)
17199             xml.writeAttribute("time", "");
17200         else
17201             xml.writeAttribute("time", formatDuration(suiteTime));
17202         xml.writeAttribute("timestamp", getCurrentTimestamp());
17203
17204         // Write properties if there are any
17205         if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
17206             auto properties = xml.scopedElement("properties");
17207             if (m_config->hasTestFilters()) {
17208                 xml.scopedElement("property")
17209                     .writeAttribute("name", "filters")
17210                     .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
17211             }
17212             if (m_config->rngSeed() != 0) {
17213                 xml.scopedElement("property")
17214                     .writeAttribute("name", "random-seed")
17215                     .writeAttribute("value", m_config->rngSeed());
17216             }
17217         }
17218
17219         // Write test cases
17220         for (auto const& child : groupNode.children)
17221             writeTestCase(*child);
17222
17223         xml.scopedElement("system-out").writeText(trim(stdOutForSuite), XmlFormatting::Newline);
17224         xml.scopedElement("system-err").writeText(trim(stdErrForSuite), XmlFormatting::Newline);
17225     }
17226
17227     void JunitReporter::writeTestCase(TestCaseNode const& testCaseNode) {
17228         TestCaseStats const& stats = testCaseNode.value;
17229
17230         // All test cases have exactly one section - which represents the
17231         // test case itself. That section may have 0-n nested sections
17232         assert(testCaseNode.children.size() == 1);
17233         SectionNode const& rootSection = *testCaseNode.children.front();
17234
17235         std::string className = stats.testInfo.className;
17236
17237         if (className.empty()) {
17238             className = fileNameTag(stats.testInfo.tags);
17239             if (className.empty())
17240                 className = "global";
17241         }
17242
17243         if (!m_config->name().empty())
17244             className = m_config->name() + "." + className;
17245
17246         writeSection(className, "", rootSection, stats.testInfo.okToFail());
17247     }
17248
17249     void JunitReporter::writeSection(std::string const& className,
17250                                      std::string const& rootName,
17251                                      SectionNode const& sectionNode,
17252                                      bool testOkToFail) {
17253         std::string name = trim(sectionNode.stats.sectionInfo.name);
17254         if (!rootName.empty())
17255             name = rootName + '/' + name;
17256
17257         if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() ||
17258             !sectionNode.stdErr.empty()) {
17259             XmlWriter::ScopedElement e = xml.scopedElement("testcase");
17260             if (className.empty()) {
17261                 xml.writeAttribute("classname", name);
17262                 xml.writeAttribute("name", "root");
17263             } else {
17264                 xml.writeAttribute("classname", className);
17265                 xml.writeAttribute("name", name);
17266             }
17267             xml.writeAttribute("time", formatDuration(sectionNode.stats.durationInSeconds));
17268             // This is not ideal, but it should be enough to mimic gtest's
17269             // junit output.
17270             // Ideally the JUnit reporter would also handle `skipTest`
17271             // events and write those out appropriately.
17272             xml.writeAttribute("status", "run");
17273
17274             if (sectionNode.stats.assertions.failedButOk) {
17275                 xml.scopedElement("skipped").writeAttribute("message",
17276                                                             "TEST_CASE tagged with !mayfail");
17277             }
17278
17279             writeAssertions(sectionNode);
17280
17281             if (!sectionNode.stdOut.empty())
17282                 xml.scopedElement("system-out")
17283                     .writeText(trim(sectionNode.stdOut), XmlFormatting::Newline);
17284             if (!sectionNode.stdErr.empty())
17285                 xml.scopedElement("system-err")
17286                     .writeText(trim(sectionNode.stdErr), XmlFormatting::Newline);
17287         }
17288         for (auto const& childNode : sectionNode.childSections)
17289             if (className.empty())
17290                 writeSection(name, "", *childNode, testOkToFail);
17291             else
17292                 writeSection(className, name, *childNode, testOkToFail);
17293     }
17294
17295     void JunitReporter::writeAssertions(SectionNode const& sectionNode) {
17296         for (auto const& assertion : sectionNode.assertions)
17297             writeAssertion(assertion);
17298     }
17299
17300     void JunitReporter::writeAssertion(AssertionStats const& stats) {
17301         AssertionResult const& result = stats.assertionResult;
17302         if (!result.isOk()) {
17303             std::string elementName;
17304             switch (result.getResultType()) {
17305                 case ResultWas::ThrewException:
17306                 case ResultWas::FatalErrorCondition:
17307                     elementName = "error";
17308                     break;
17309                 case ResultWas::ExplicitFailure:
17310                 case ResultWas::ExpressionFailed:
17311                 case ResultWas::DidntThrowException:
17312                     elementName = "failure";
17313                     break;
17314
17315                 // We should never see these here:
17316                 case ResultWas::Info:
17317                 case ResultWas::Warning:
17318                 case ResultWas::Ok:
17319                 case ResultWas::Unknown:
17320                 case ResultWas::FailureBit:
17321                 case ResultWas::Exception:
17322                     elementName = "internalError";
17323                     break;
17324             }
17325
17326             XmlWriter::ScopedElement e = xml.scopedElement(elementName);
17327
17328             xml.writeAttribute("message", result.getExpression());
17329             xml.writeAttribute("type", result.getTestMacroName());
17330
17331             ReusableStringStream rss;
17332             if (stats.totals.assertions.total() > 0) {
17333                 rss << "FAILED"
17334                     << ":\n";
17335                 if (result.hasExpression()) {
17336                     rss << "  ";
17337                     rss << result.getExpressionInMacro();
17338                     rss << '\n';
17339                 }
17340                 if (result.hasExpandedExpression()) {
17341                     rss << "with expansion:\n";
17342                     rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17343                 }
17344             } else {
17345                 rss << '\n';
17346             }
17347
17348             if (!result.getMessage().empty())
17349                 rss << result.getMessage() << '\n';
17350             for (auto const& msg : stats.infoMessages)
17351                 if (msg.type == ResultWas::Info)
17352                     rss << msg.message << '\n';
17353
17354             rss << "at " << result.getSourceInfo();
17355             xml.writeText(rss.str(), XmlFormatting::Newline);
17356         }
17357     }
17358
17359     CATCH_REGISTER_REPORTER("junit", JunitReporter)
17360
17361 } // end namespace Catch
17362 // end catch_reporter_junit.cpp
17363 // start catch_reporter_listening.cpp
17364
17365 #include <cassert>
17366
17367 namespace Catch {
17368
17369     ListeningReporter::ListeningReporter() {
17370         // We will assume that listeners will always want all assertions
17371         m_preferences.shouldReportAllAssertions = true;
17372     }
17373
17374     void ListeningReporter::addListener(IStreamingReporterPtr&& listener) {
17375         m_listeners.push_back(std::move(listener));
17376     }
17377
17378     void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17379         assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17380         m_reporter = std::move(reporter);
17381         m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17382     }
17383
17384     ReporterPreferences ListeningReporter::getPreferences() const { return m_preferences; }
17385
17386     std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17387         return std::set<Verbosity>{};
17388     }
17389
17390     void ListeningReporter::noMatchingTestCases(std::string const& spec) {
17391         for (auto const& listener : m_listeners) {
17392             listener->noMatchingTestCases(spec);
17393         }
17394         m_reporter->noMatchingTestCases(spec);
17395     }
17396
17397     void ListeningReporter::reportInvalidArguments(std::string const& arg) {
17398         for (auto const& listener : m_listeners) {
17399             listener->reportInvalidArguments(arg);
17400         }
17401         m_reporter->reportInvalidArguments(arg);
17402     }
17403
17404 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17405     void ListeningReporter::benchmarkPreparing(std::string const& name) {
17406         for (auto const& listener : m_listeners) {
17407             listener->benchmarkPreparing(name);
17408         }
17409         m_reporter->benchmarkPreparing(name);
17410     }
17411     void ListeningReporter::benchmarkStarting(BenchmarkInfo const& benchmarkInfo) {
17412         for (auto const& listener : m_listeners) {
17413             listener->benchmarkStarting(benchmarkInfo);
17414         }
17415         m_reporter->benchmarkStarting(benchmarkInfo);
17416     }
17417     void ListeningReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17418         for (auto const& listener : m_listeners) {
17419             listener->benchmarkEnded(benchmarkStats);
17420         }
17421         m_reporter->benchmarkEnded(benchmarkStats);
17422     }
17423
17424     void ListeningReporter::benchmarkFailed(std::string const& error) {
17425         for (auto const& listener : m_listeners) {
17426             listener->benchmarkFailed(error);
17427         }
17428         m_reporter->benchmarkFailed(error);
17429     }
17430 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17431
17432     void ListeningReporter::testRunStarting(TestRunInfo const& testRunInfo) {
17433         for (auto const& listener : m_listeners) {
17434             listener->testRunStarting(testRunInfo);
17435         }
17436         m_reporter->testRunStarting(testRunInfo);
17437     }
17438
17439     void ListeningReporter::testGroupStarting(GroupInfo const& groupInfo) {
17440         for (auto const& listener : m_listeners) {
17441             listener->testGroupStarting(groupInfo);
17442         }
17443         m_reporter->testGroupStarting(groupInfo);
17444     }
17445
17446     void ListeningReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17447         for (auto const& listener : m_listeners) {
17448             listener->testCaseStarting(testInfo);
17449         }
17450         m_reporter->testCaseStarting(testInfo);
17451     }
17452
17453     void ListeningReporter::sectionStarting(SectionInfo const& sectionInfo) {
17454         for (auto const& listener : m_listeners) {
17455             listener->sectionStarting(sectionInfo);
17456         }
17457         m_reporter->sectionStarting(sectionInfo);
17458     }
17459
17460     void ListeningReporter::assertionStarting(AssertionInfo const& assertionInfo) {
17461         for (auto const& listener : m_listeners) {
17462             listener->assertionStarting(assertionInfo);
17463         }
17464         m_reporter->assertionStarting(assertionInfo);
17465     }
17466
17467     // The return value indicates if the messages buffer should be cleared:
17468     bool ListeningReporter::assertionEnded(AssertionStats const& assertionStats) {
17469         for (auto const& listener : m_listeners) {
17470             static_cast<void>(listener->assertionEnded(assertionStats));
17471         }
17472         return m_reporter->assertionEnded(assertionStats);
17473     }
17474
17475     void ListeningReporter::sectionEnded(SectionStats const& sectionStats) {
17476         for (auto const& listener : m_listeners) {
17477             listener->sectionEnded(sectionStats);
17478         }
17479         m_reporter->sectionEnded(sectionStats);
17480     }
17481
17482     void ListeningReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17483         for (auto const& listener : m_listeners) {
17484             listener->testCaseEnded(testCaseStats);
17485         }
17486         m_reporter->testCaseEnded(testCaseStats);
17487     }
17488
17489     void ListeningReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17490         for (auto const& listener : m_listeners) {
17491             listener->testGroupEnded(testGroupStats);
17492         }
17493         m_reporter->testGroupEnded(testGroupStats);
17494     }
17495
17496     void ListeningReporter::testRunEnded(TestRunStats const& testRunStats) {
17497         for (auto const& listener : m_listeners) {
17498             listener->testRunEnded(testRunStats);
17499         }
17500         m_reporter->testRunEnded(testRunStats);
17501     }
17502
17503     void ListeningReporter::skipTest(TestCaseInfo const& testInfo) {
17504         for (auto const& listener : m_listeners) {
17505             listener->skipTest(testInfo);
17506         }
17507         m_reporter->skipTest(testInfo);
17508     }
17509
17510     bool ListeningReporter::isMulti() const { return true; }
17511
17512 } // end namespace Catch
17513 // end catch_reporter_listening.cpp
17514 // start catch_reporter_xml.cpp
17515
17516 #if defined(_MSC_VER)
17517 #pragma warning(push)
17518 #pragma warning(disable : 4061) // Not all labels are EXPLICITLY handled in
17519                                 // switch Note that 4062 (not all labels are
17520                                 // handled and default is missing) is enabled
17521 #endif
17522
17523 namespace Catch {
17524     XmlReporter::XmlReporter(ReporterConfig const& _config) :
17525         StreamingReporterBase(_config), m_xml(_config.stream()) {
17526         m_reporterPrefs.shouldRedirectStdOut = true;
17527         m_reporterPrefs.shouldReportAllAssertions = true;
17528     }
17529
17530     XmlReporter::~XmlReporter() = default;
17531
17532     std::string XmlReporter::getDescription() { return "Reports test results as an XML document"; }
17533
17534     std::string XmlReporter::getStylesheetRef() const { return std::string(); }
17535
17536     void XmlReporter::writeSourceInfo(SourceLineInfo const& sourceInfo) {
17537         m_xml.writeAttribute("filename", sourceInfo.file).writeAttribute("line", sourceInfo.line);
17538     }
17539
17540     void XmlReporter::noMatchingTestCases(std::string const& s) {
17541         StreamingReporterBase::noMatchingTestCases(s);
17542     }
17543
17544     void XmlReporter::testRunStarting(TestRunInfo const& testInfo) {
17545         StreamingReporterBase::testRunStarting(testInfo);
17546         std::string stylesheetRef = getStylesheetRef();
17547         if (!stylesheetRef.empty())
17548             m_xml.writeStylesheetRef(stylesheetRef);
17549         m_xml.startElement("Catch");
17550         if (!m_config->name().empty())
17551             m_xml.writeAttribute("name", m_config->name());
17552         if (m_config->testSpec().hasFilters())
17553             m_xml.writeAttribute("filters", serializeFilters(m_config->getTestsOrTags()));
17554         if (m_config->rngSeed() != 0)
17555             m_xml.scopedElement("Randomness").writeAttribute("seed", m_config->rngSeed());
17556     }
17557
17558     void XmlReporter::testGroupStarting(GroupInfo const& groupInfo) {
17559         StreamingReporterBase::testGroupStarting(groupInfo);
17560         m_xml.startElement("Group").writeAttribute("name", groupInfo.name);
17561     }
17562
17563     void XmlReporter::testCaseStarting(TestCaseInfo const& testInfo) {
17564         StreamingReporterBase::testCaseStarting(testInfo);
17565         m_xml.startElement("TestCase")
17566             .writeAttribute("name", trim(testInfo.name))
17567             .writeAttribute("description", testInfo.description)
17568             .writeAttribute("tags", testInfo.tagsAsString());
17569
17570         writeSourceInfo(testInfo.lineInfo);
17571
17572         if (m_config->showDurations() == ShowDurations::Always)
17573             m_testCaseTimer.start();
17574         m_xml.ensureTagClosed();
17575     }
17576
17577     void XmlReporter::sectionStarting(SectionInfo const& sectionInfo) {
17578         StreamingReporterBase::sectionStarting(sectionInfo);
17579         if (m_sectionDepth++ > 0) {
17580             m_xml.startElement("Section").writeAttribute("name", trim(sectionInfo.name));
17581             writeSourceInfo(sectionInfo.lineInfo);
17582             m_xml.ensureTagClosed();
17583         }
17584     }
17585
17586     void XmlReporter::assertionStarting(AssertionInfo const&) {}
17587
17588     bool XmlReporter::assertionEnded(AssertionStats const& assertionStats) {
17589
17590         AssertionResult const& result = assertionStats.assertionResult;
17591
17592         bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17593
17594         if (includeResults || result.getResultType() == ResultWas::Warning) {
17595             // Print any info messages in <Info> tags.
17596             for (auto const& msg : assertionStats.infoMessages) {
17597                 if (msg.type == ResultWas::Info && includeResults) {
17598                     m_xml.scopedElement("Info").writeText(msg.message);
17599                 } else if (msg.type == ResultWas::Warning) {
17600                     m_xml.scopedElement("Warning").writeText(msg.message);
17601                 }
17602             }
17603         }
17604
17605         // Drop out if result was successful but we're not printing them.
17606         if (!includeResults && result.getResultType() != ResultWas::Warning)
17607             return true;
17608
17609         // Print the expression if there is one.
17610         if (result.hasExpression()) {
17611             m_xml.startElement("Expression")
17612                 .writeAttribute("success", result.succeeded())
17613                 .writeAttribute("type", result.getTestMacroName());
17614
17615             writeSourceInfo(result.getSourceInfo());
17616
17617             m_xml.scopedElement("Original").writeText(result.getExpression());
17618             m_xml.scopedElement("Expanded").writeText(result.getExpandedExpression());
17619         }
17620
17621         // And... Print a result applicable to each result type.
17622         switch (result.getResultType()) {
17623             case ResultWas::ThrewException:
17624                 m_xml.startElement("Exception");
17625                 writeSourceInfo(result.getSourceInfo());
17626                 m_xml.writeText(result.getMessage());
17627                 m_xml.endElement();
17628                 break;
17629             case ResultWas::FatalErrorCondition:
17630                 m_xml.startElement("FatalErrorCondition");
17631                 writeSourceInfo(result.getSourceInfo());
17632                 m_xml.writeText(result.getMessage());
17633                 m_xml.endElement();
17634                 break;
17635             case ResultWas::Info:
17636                 m_xml.scopedElement("Info").writeText(result.getMessage());
17637                 break;
17638             case ResultWas::Warning:
17639                 // Warning will already have been written
17640                 break;
17641             case ResultWas::ExplicitFailure:
17642                 m_xml.startElement("Failure");
17643                 writeSourceInfo(result.getSourceInfo());
17644                 m_xml.writeText(result.getMessage());
17645                 m_xml.endElement();
17646                 break;
17647             default:
17648                 break;
17649         }
17650
17651         if (result.hasExpression())
17652             m_xml.endElement();
17653
17654         return true;
17655     }
17656
17657     void XmlReporter::sectionEnded(SectionStats const& sectionStats) {
17658         StreamingReporterBase::sectionEnded(sectionStats);
17659         if (--m_sectionDepth > 0) {
17660             XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults");
17661             e.writeAttribute("successes", sectionStats.assertions.passed);
17662             e.writeAttribute("failures", sectionStats.assertions.failed);
17663             e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk);
17664
17665             if (m_config->showDurations() == ShowDurations::Always)
17666                 e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds);
17667
17668             m_xml.endElement();
17669         }
17670     }
17671
17672     void XmlReporter::testCaseEnded(TestCaseStats const& testCaseStats) {
17673         StreamingReporterBase::testCaseEnded(testCaseStats);
17674         XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult");
17675         e.writeAttribute("success", testCaseStats.totals.assertions.allOk());
17676
17677         if (m_config->showDurations() == ShowDurations::Always)
17678             e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds());
17679
17680         if (!testCaseStats.stdOut.empty())
17681             m_xml.scopedElement("StdOut").writeText(trim(testCaseStats.stdOut),
17682                                                     XmlFormatting::Newline);
17683         if (!testCaseStats.stdErr.empty())
17684             m_xml.scopedElement("StdErr").writeText(trim(testCaseStats.stdErr),
17685                                                     XmlFormatting::Newline);
17686
17687         m_xml.endElement();
17688     }
17689
17690     void XmlReporter::testGroupEnded(TestGroupStats const& testGroupStats) {
17691         StreamingReporterBase::testGroupEnded(testGroupStats);
17692         // TODO: Check testGroupStats.aborting and act accordingly.
17693         m_xml.scopedElement("OverallResults")
17694             .writeAttribute("successes", testGroupStats.totals.assertions.passed)
17695             .writeAttribute("failures", testGroupStats.totals.assertions.failed)
17696             .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk);
17697         m_xml.scopedElement("OverallResultsCases")
17698             .writeAttribute("successes", testGroupStats.totals.testCases.passed)
17699             .writeAttribute("failures", testGroupStats.totals.testCases.failed)
17700             .writeAttribute("expectedFailures", testGroupStats.totals.testCases.failedButOk);
17701         m_xml.endElement();
17702     }
17703
17704     void XmlReporter::testRunEnded(TestRunStats const& testRunStats) {
17705         StreamingReporterBase::testRunEnded(testRunStats);
17706         m_xml.scopedElement("OverallResults")
17707             .writeAttribute("successes", testRunStats.totals.assertions.passed)
17708             .writeAttribute("failures", testRunStats.totals.assertions.failed)
17709             .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk);
17710         m_xml.scopedElement("OverallResultsCases")
17711             .writeAttribute("successes", testRunStats.totals.testCases.passed)
17712             .writeAttribute("failures", testRunStats.totals.testCases.failed)
17713             .writeAttribute("expectedFailures", testRunStats.totals.testCases.failedButOk);
17714         m_xml.endElement();
17715     }
17716
17717 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17718     void XmlReporter::benchmarkPreparing(std::string const& name) {
17719         m_xml.startElement("BenchmarkResults").writeAttribute("name", name);
17720     }
17721
17722     void XmlReporter::benchmarkStarting(BenchmarkInfo const& info) {
17723         m_xml.writeAttribute("samples", info.samples)
17724             .writeAttribute("resamples", info.resamples)
17725             .writeAttribute("iterations", info.iterations)
17726             .writeAttribute("clockResolution", info.clockResolution)
17727             .writeAttribute("estimatedDuration", info.estimatedDuration)
17728             .writeComment("All values in nano seconds");
17729     }
17730
17731     void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17732         m_xml.startElement("mean")
17733             .writeAttribute("value", benchmarkStats.mean.point.count())
17734             .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17735             .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17736             .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17737         m_xml.endElement();
17738         m_xml.startElement("standardDeviation")
17739             .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17740             .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17741             .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17742             .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17743         m_xml.endElement();
17744         m_xml.startElement("outliers")
17745             .writeAttribute("variance", benchmarkStats.outlierVariance)
17746             .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17747             .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17748             .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17749             .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17750         m_xml.endElement();
17751         m_xml.endElement();
17752     }
17753
17754     void XmlReporter::benchmarkFailed(std::string const& error) {
17755         m_xml.scopedElement("failed").writeAttribute("message", error);
17756         m_xml.endElement();
17757     }
17758 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17759
17760     CATCH_REGISTER_REPORTER("xml", XmlReporter)
17761
17762 } // end namespace Catch
17763
17764 #if defined(_MSC_VER)
17765 #pragma warning(pop)
17766 #endif
17767 // end catch_reporter_xml.cpp
17768
17769 namespace Catch {
17770     LeakDetector leakDetector;
17771 }
17772
17773 #ifdef __clang__
17774 #pragma clang diagnostic pop
17775 #endif
17776
17777 // end catch_impl.hpp
17778 #endif
17779
17780 #ifdef CATCH_CONFIG_MAIN
17781 // start catch_default_main.hpp
17782
17783 #ifndef __OBJC__
17784
17785 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) &&         \
17786     !defined(DO_NOT_USE_WMAIN)
17787 // Standard C/C++ Win32 Unicode wmain entry point
17788 extern "C" int wmain(int argc, wchar_t* argv[], wchar_t*[]) {
17789 #else
17790 // Standard C/C++ main entry point
17791 int main(int argc, char* argv[]) {
17792 #endif
17793
17794     return Catch::Session().run(argc, argv);
17795 }
17796
17797 #else // __OBJC__
17798
17799 // Objective-C entry point
17800 int main(int argc, char* const argv[]) {
17801 #if !CATCH_ARC_ENABLED
17802     NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
17803 #endif
17804
17805     Catch::registerTestMethods();
17806     int result = Catch::Session().run(argc, (char**)argv);
17807
17808 #if !CATCH_ARC_ENABLED
17809     [pool drain];
17810 #endif
17811
17812     return result;
17813 }
17814
17815 #endif // __OBJC__
17816
17817 // end catch_default_main.hpp
17818 #endif
17819
17820 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17821
17822 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17823 #undef CLARA_CONFIG_MAIN
17824 #endif
17825
17826 #if !defined(CATCH_CONFIG_DISABLE)
17827 //////
17828 // If this config identifier is defined then all CATCH macros are prefixed with
17829 // CATCH_
17830 #ifdef CATCH_CONFIG_PREFIX_ALL
17831
17832 #define CATCH_REQUIRE(...)                                                                         \
17833     INTERNAL_CATCH_TEST("CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17834 #define CATCH_REQUIRE_FALSE(...)                                                                   \
17835     INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE",                                                     \
17836                         Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest,    \
17837                         __VA_ARGS__)
17838
17839 #define CATCH_REQUIRE_THROWS(...)                                                                  \
17840     INTERNAL_CATCH_THROWS("CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17841 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType)                                               \
17842     INTERNAL_CATCH_THROWS_AS(                                                                      \
17843         "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr)
17844 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher)                                                   \
17845     INTERNAL_CATCH_THROWS_STR_MATCHES(                                                             \
17846         "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr)
17847 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17848 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher)                                 \
17849     INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES",                                  \
17850                                   exceptionType,                                                   \
17851                                   Catch::ResultDisposition::Normal,                                \
17852                                   matcher,                                                         \
17853                                   expr)
17854 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17855 #define CATCH_REQUIRE_NOTHROW(...)                                                                 \
17856     INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17857
17858 #define CATCH_CHECK(...)                                                                           \
17859     INTERNAL_CATCH_TEST("CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17860 #define CATCH_CHECK_FALSE(...)                                                                     \
17861     INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE",                                                       \
17862                         Catch::ResultDisposition::ContinueOnFailure |                              \
17863                             Catch::ResultDisposition::FalseTest,                                   \
17864                         __VA_ARGS__)
17865 #define CATCH_CHECKED_IF(...)                                                                      \
17866     INTERNAL_CATCH_IF("CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17867 #define CATCH_CHECKED_ELSE(...)                                                                    \
17868     INTERNAL_CATCH_ELSE(                                                                           \
17869         "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17870 #define CATCH_CHECK_NOFAIL(...)                                                                    \
17871     INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL",                                                      \
17872                         Catch::ResultDisposition::ContinueOnFailure |                              \
17873                             Catch::ResultDisposition::SuppressFail,                                \
17874                         __VA_ARGS__)
17875
17876 #define CATCH_CHECK_THROWS(...)                                                                    \
17877     INTERNAL_CATCH_THROWS(                                                                         \
17878         "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17879 #define CATCH_CHECK_THROWS_AS(expr, exceptionType)                                                 \
17880     INTERNAL_CATCH_THROWS_AS(                                                                      \
17881         "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr)
17882 #define CATCH_CHECK_THROWS_WITH(expr, matcher)                                                     \
17883     INTERNAL_CATCH_THROWS_STR_MATCHES(                                                             \
17884         "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17885 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17886 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher)                                   \
17887     INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES",                                    \
17888                                   exceptionType,                                                   \
17889                                   Catch::ResultDisposition::ContinueOnFailure,                     \
17890                                   matcher,                                                         \
17891                                   expr)
17892 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17893 #define CATCH_CHECK_NOTHROW(...)                                                                   \
17894     INTERNAL_CATCH_NO_THROW(                                                                       \
17895         "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17896
17897 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17898 #define CATCH_CHECK_THAT(arg, matcher)                                                             \
17899     INTERNAL_CHECK_THAT(                                                                           \
17900         "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
17901
17902 #define CATCH_REQUIRE_THAT(arg, matcher)                                                           \
17903     INTERNAL_CHECK_THAT("CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17904 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17905
17906 #define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg)
17907 #define CATCH_UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg)
17908 #define CATCH_WARN(msg)                                                                            \
17909     INTERNAL_CATCH_MSG(                                                                            \
17910         "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg)
17911 #define CATCH_CAPTURE(...)                                                                         \
17912     INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__)
17913
17914 #define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17915 #define CATCH_TEST_CASE_METHOD(className, ...)                                                     \
17916     INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17917 #define CATCH_METHOD_AS_TEST_CASE(method, ...)                                                     \
17918     INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17919 #define CATCH_REGISTER_TEST_CASE(Function, ...)                                                    \
17920     INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17921 #define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17922 #define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17923 #define CATCH_FAIL(...)                                                                            \
17924     INTERNAL_CATCH_MSG("CATCH_FAIL",                                                               \
17925                        Catch::ResultWas::ExplicitFailure,                                          \
17926                        Catch::ResultDisposition::Normal,                                           \
17927                        __VA_ARGS__)
17928 #define CATCH_FAIL_CHECK(...)                                                                      \
17929     INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK",                                                         \
17930                        Catch::ResultWas::ExplicitFailure,                                          \
17931                        Catch::ResultDisposition::ContinueOnFailure,                                \
17932                        __VA_ARGS__)
17933 #define CATCH_SUCCEED(...)                                                                         \
17934     INTERNAL_CATCH_MSG("CATCH_SUCCEED",                                                            \
17935                        Catch::ResultWas::Ok,                                                       \
17936                        Catch::ResultDisposition::ContinueOnFailure,                                \
17937                        __VA_ARGS__)
17938
17939 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17940
17941 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17942 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17943 #define CATCH_TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17944 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...)                                            \
17945     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17946 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                        \
17947     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17948 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17949 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...)                                                  \
17950     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17951 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                    \
17952     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17953 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                \
17954     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17955 #else
17956 #define CATCH_TEMPLATE_TEST_CASE(...)                                                              \
17957     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17958 #define CATCH_TEMPLATE_TEST_CASE_SIG(...)                                                          \
17959     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17960 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...)                                            \
17961     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17962 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                        \
17963     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
17964         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17965 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...)                                                      \
17966     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17967 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...)                                                  \
17968     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17969 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                    \
17970     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
17971         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17972 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                \
17973     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
17974         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17975 #endif
17976
17977 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17978 #define CATCH_STATIC_REQUIRE(...)                                                                  \
17979     static_assert(__VA_ARGS__, #__VA_ARGS__);                                                      \
17980     CATCH_SUCCEED(#__VA_ARGS__)
17981 #define CATCH_STATIC_REQUIRE_FALSE(...)                                                            \
17982     static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")");                                          \
17983     CATCH_SUCCEED(#__VA_ARGS__)
17984 #else
17985 #define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__)
17986 #define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__)
17987 #endif
17988
17989 // "BDD-style" convenience wrappers
17990 #define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__)
17991 #define CATCH_SCENARIO_METHOD(className, ...)                                                      \
17992     INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17993 #define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("    Given: " << desc)
17994 #define CATCH_AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17995 #define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("     When: " << desc)
17996 #define CATCH_AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17997 #define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("     Then: " << desc)
17998 #define CATCH_AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("      And: " << desc)
17999
18000 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18001 #define CATCH_BENCHMARK(...)                                                                       \
18002     INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____),           \
18003                              INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ),                            \
18004                              INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18005 #define CATCH_BENCHMARK_ADVANCED(name)                                                             \
18006     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____),  \
18007                                       name)
18008 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18009
18010 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
18011 // required
18012 #else
18013
18014 #define REQUIRE(...) INTERNAL_CATCH_TEST("REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
18015 #define REQUIRE_FALSE(...)                                                                         \
18016     INTERNAL_CATCH_TEST("REQUIRE_FALSE",                                                           \
18017                         Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest,    \
18018                         __VA_ARGS__)
18019
18020 #define REQUIRE_THROWS(...)                                                                        \
18021     INTERNAL_CATCH_THROWS("REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
18022 #define REQUIRE_THROWS_AS(expr, exceptionType)                                                     \
18023     INTERNAL_CATCH_THROWS_AS(                                                                      \
18024         "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr)
18025 #define REQUIRE_THROWS_WITH(expr, matcher)                                                         \
18026     INTERNAL_CATCH_THROWS_STR_MATCHES(                                                             \
18027         "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr)
18028 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18029 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher)                                       \
18030     INTERNAL_CATCH_THROWS_MATCHES(                                                                 \
18031         "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr)
18032 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18033 #define REQUIRE_NOTHROW(...)                                                                       \
18034     INTERNAL_CATCH_NO_THROW("REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
18035
18036 #define CHECK(...)                                                                                 \
18037     INTERNAL_CATCH_TEST("CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18038 #define CHECK_FALSE(...)                                                                           \
18039     INTERNAL_CATCH_TEST("CHECK_FALSE",                                                             \
18040                         Catch::ResultDisposition::ContinueOnFailure |                              \
18041                             Catch::ResultDisposition::FalseTest,                                   \
18042                         __VA_ARGS__)
18043 #define CHECKED_IF(...)                                                                            \
18044     INTERNAL_CATCH_IF("CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18045 #define CHECKED_ELSE(...)                                                                          \
18046     INTERNAL_CATCH_ELSE("CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18047 #define CHECK_NOFAIL(...)                                                                          \
18048     INTERNAL_CATCH_TEST("CHECK_NOFAIL",                                                            \
18049                         Catch::ResultDisposition::ContinueOnFailure |                              \
18050                             Catch::ResultDisposition::SuppressFail,                                \
18051                         __VA_ARGS__)
18052
18053 #define CHECK_THROWS(...)                                                                          \
18054     INTERNAL_CATCH_THROWS("CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18055 #define CHECK_THROWS_AS(expr, exceptionType)                                                       \
18056     INTERNAL_CATCH_THROWS_AS(                                                                      \
18057         "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr)
18058 #define CHECK_THROWS_WITH(expr, matcher)                                                           \
18059     INTERNAL_CATCH_THROWS_STR_MATCHES(                                                             \
18060         "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
18061 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18062 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher)                                         \
18063     INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES",                                          \
18064                                   exceptionType,                                                   \
18065                                   Catch::ResultDisposition::ContinueOnFailure,                     \
18066                                   matcher,                                                         \
18067                                   expr)
18068 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18069 #define CHECK_NOTHROW(...)                                                                         \
18070     INTERNAL_CATCH_NO_THROW(                                                                       \
18071         "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18072
18073 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18074 #define CHECK_THAT(arg, matcher)                                                                   \
18075     INTERNAL_CHECK_THAT("CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
18076
18077 #define REQUIRE_THAT(arg, matcher)                                                                 \
18078     INTERNAL_CHECK_THAT("REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
18079 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18080
18081 #define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg)
18082 #define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg)
18083 #define WARN(msg)                                                                                  \
18084     INTERNAL_CATCH_MSG(                                                                            \
18085         "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg)
18086 #define CAPTURE(...)                                                                               \
18087     INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__)
18088
18089 #define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
18090 #define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
18091 #define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
18092 #define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
18093 #define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
18094 #define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
18095 #define FAIL(...)                                                                                  \
18096     INTERNAL_CATCH_MSG(                                                                            \
18097         "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__)
18098 #define FAIL_CHECK(...)                                                                            \
18099     INTERNAL_CATCH_MSG("FAIL_CHECK",                                                               \
18100                        Catch::ResultWas::ExplicitFailure,                                          \
18101                        Catch::ResultDisposition::ContinueOnFailure,                                \
18102                        __VA_ARGS__)
18103 #define SUCCEED(...)                                                                               \
18104     INTERNAL_CATCH_MSG(                                                                            \
18105         "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
18106 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
18107
18108 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18109 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18110 #define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
18111 #define TEMPLATE_TEST_CASE_METHOD(className, ...)                                                  \
18112     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18113 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                              \
18114     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18115 #define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
18116 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...)                                                        \
18117     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
18118 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                          \
18119     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
18120 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                      \
18121     INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
18122 #define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
18123 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...)                                             \
18124     INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)
18125 #else
18126 #define TEMPLATE_TEST_CASE(...)                                                                    \
18127     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
18128 #define TEMPLATE_TEST_CASE_SIG(...)                                                                \
18129     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
18130 #define TEMPLATE_TEST_CASE_METHOD(className, ...)                                                  \
18131     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
18132 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                              \
18133     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18134         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18135 #define TEMPLATE_PRODUCT_TEST_CASE(...)                                                            \
18136     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
18137 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...)                                                        \
18138     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
18139 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                          \
18140     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18141         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
18142 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                      \
18143     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18144         INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
18145 #define TEMPLATE_LIST_TEST_CASE(...)                                                               \
18146     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__))
18147 #define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...)                                             \
18148     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18149         INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__))
18150 #endif
18151
18152 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
18153 #define STATIC_REQUIRE(...)                                                                        \
18154     static_assert(__VA_ARGS__, #__VA_ARGS__);                                                      \
18155     SUCCEED(#__VA_ARGS__)
18156 #define STATIC_REQUIRE_FALSE(...)                                                                  \
18157     static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")");                                          \
18158     SUCCEED("!(" #__VA_ARGS__ ")")
18159 #else
18160 #define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__)
18161 #define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__)
18162 #endif
18163
18164 #endif
18165
18166 #define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)
18167
18168 // "BDD-style" convenience wrappers
18169 #define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__)
18170 #define SCENARIO_METHOD(className, ...)                                                            \
18171     INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
18172
18173 #define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("    Given: " << desc)
18174 #define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
18175 #define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("     When: " << desc)
18176 #define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
18177 #define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("     Then: " << desc)
18178 #define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("      And: " << desc)
18179
18180 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
18181 #define BENCHMARK(...)                                                                             \
18182     INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____),           \
18183                              INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ),                            \
18184                              INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
18185 #define BENCHMARK_ADVANCED(name)                                                                   \
18186     INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____),  \
18187                                       name)
18188 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
18189
18190 using Catch::Detail::Approx;
18191
18192 #else // CATCH_CONFIG_DISABLE
18193
18194 //////
18195 // If this config identifier is defined then all CATCH macros are prefixed with
18196 // CATCH_
18197 #ifdef CATCH_CONFIG_PREFIX_ALL
18198
18199 #define CATCH_REQUIRE(...) (void)(0)
18200 #define CATCH_REQUIRE_FALSE(...) (void)(0)
18201
18202 #define CATCH_REQUIRE_THROWS(...) (void)(0)
18203 #define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18204 #define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18205 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18206 #define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18207 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18208 #define CATCH_REQUIRE_NOTHROW(...) (void)(0)
18209
18210 #define CATCH_CHECK(...) (void)(0)
18211 #define CATCH_CHECK_FALSE(...) (void)(0)
18212 #define CATCH_CHECKED_IF(...) if (__VA_ARGS__)
18213 #define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__))
18214 #define CATCH_CHECK_NOFAIL(...) (void)(0)
18215
18216 #define CATCH_CHECK_THROWS(...) (void)(0)
18217 #define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18218 #define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0)
18219 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18220 #define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18221 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18222 #define CATCH_CHECK_NOTHROW(...) (void)(0)
18223
18224 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18225 #define CATCH_CHECK_THAT(arg, matcher) (void)(0)
18226
18227 #define CATCH_REQUIRE_THAT(arg, matcher) (void)(0)
18228 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18229
18230 #define CATCH_INFO(msg) (void)(0)
18231 #define CATCH_UNSCOPED_INFO(msg) (void)(0)
18232 #define CATCH_WARN(msg) (void)(0)
18233 #define CATCH_CAPTURE(msg) (void)(0)
18234
18235 #define CATCH_TEST_CASE(...)                                                                       \
18236     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18237         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18238 #define CATCH_TEST_CASE_METHOD(className, ...)                                                     \
18239     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18240         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18241 #define CATCH_METHOD_AS_TEST_CASE(method, ...)
18242 #define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0)
18243 #define CATCH_SECTION(...)
18244 #define CATCH_DYNAMIC_SECTION(...)
18245 #define CATCH_FAIL(...) (void)(0)
18246 #define CATCH_FAIL_CHECK(...) (void)(0)
18247 #define CATCH_SUCCEED(...) (void)(0)
18248
18249 #define CATCH_ANON_TEST_CASE()                                                                     \
18250     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18251         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18252
18253 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18254 #define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18255 #define CATCH_TEMPLATE_TEST_CASE_SIG(...)                                                          \
18256     INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18257 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...)                                            \
18258     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18259 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                        \
18260     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18261 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18262 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18263 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                    \
18264     CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18265 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                \
18266     CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18267 #else
18268 #define CATCH_TEMPLATE_TEST_CASE(...)                                                              \
18269     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18270 #define CATCH_TEMPLATE_TEST_CASE_SIG(...)                                                          \
18271     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18272 #define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...)                                            \
18273     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18274         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18275 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                        \
18276     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18277         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18278 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18279 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
18280 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                    \
18281     CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18282 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                \
18283     CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18284 #endif
18285
18286 // "BDD-style" convenience wrappers
18287 #define CATCH_SCENARIO(...)                                                                        \
18288     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18289         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18290 #define CATCH_SCENARIO_METHOD(className, ...)                                                      \
18291     INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(                                                \
18292         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18293 #define CATCH_GIVEN(desc)
18294 #define CATCH_AND_GIVEN(desc)
18295 #define CATCH_WHEN(desc)
18296 #define CATCH_AND_WHEN(desc)
18297 #define CATCH_THEN(desc)
18298 #define CATCH_AND_THEN(desc)
18299
18300 #define CATCH_STATIC_REQUIRE(...) (void)(0)
18301 #define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0)
18302
18303 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not
18304 // required
18305 #else
18306
18307 #define REQUIRE(...) (void)(0)
18308 #define REQUIRE_FALSE(...) (void)(0)
18309
18310 #define REQUIRE_THROWS(...) (void)(0)
18311 #define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
18312 #define REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
18313 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18314 #define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18315 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18316 #define REQUIRE_NOTHROW(...) (void)(0)
18317
18318 #define CHECK(...) (void)(0)
18319 #define CHECK_FALSE(...) (void)(0)
18320 #define CHECKED_IF(...) if (__VA_ARGS__)
18321 #define CHECKED_ELSE(...) if (!(__VA_ARGS__))
18322 #define CHECK_NOFAIL(...) (void)(0)
18323
18324 #define CHECK_THROWS(...) (void)(0)
18325 #define CHECK_THROWS_AS(expr, exceptionType) (void)(0)
18326 #define CHECK_THROWS_WITH(expr, matcher) (void)(0)
18327 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18328 #define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
18329 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18330 #define CHECK_NOTHROW(...) (void)(0)
18331
18332 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
18333 #define CHECK_THAT(arg, matcher) (void)(0)
18334
18335 #define REQUIRE_THAT(arg, matcher) (void)(0)
18336 #endif // CATCH_CONFIG_DISABLE_MATCHERS
18337
18338 #define INFO(msg) (void)(0)
18339 #define UNSCOPED_INFO(msg) (void)(0)
18340 #define WARN(msg) (void)(0)
18341 #define CAPTURE(msg) (void)(0)
18342
18343 #define TEST_CASE(...)                                                                             \
18344     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18345         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18346 #define TEST_CASE_METHOD(className, ...)                                                           \
18347     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18348         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18349 #define METHOD_AS_TEST_CASE(method, ...)
18350 #define REGISTER_TEST_CASE(Function, ...) (void)(0)
18351 #define SECTION(...)
18352 #define DYNAMIC_SECTION(...)
18353 #define FAIL(...) (void)(0)
18354 #define FAIL_CHECK(...) (void)(0)
18355 #define SUCCEED(...) (void)(0)
18356 #define ANON_TEST_CASE()                                                                           \
18357     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18358         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18359
18360 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18361 #define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18362 #define TEMPLATE_TEST_CASE_SIG(...)                                                                \
18363     INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18364 #define TEMPLATE_TEST_CASE_METHOD(className, ...)                                                  \
18365     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18366 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                              \
18367     INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18368 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18369 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18370 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                          \
18371     TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18372 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                      \
18373     TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18374 #else
18375 #define TEMPLATE_TEST_CASE(...)                                                                    \
18376     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18377 #define TEMPLATE_TEST_CASE_SIG(...)                                                                \
18378     INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18379 #define TEMPLATE_TEST_CASE_METHOD(className, ...)                                                  \
18380     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18381         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18382 #define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...)                                              \
18383     INTERNAL_CATCH_EXPAND_VARGS(                                                                   \
18384         INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18385 #define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18386 #define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18387 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...)                                          \
18388     TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18389 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...)                                      \
18390     TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18391 #endif
18392
18393 #define STATIC_REQUIRE(...) (void)(0)
18394 #define STATIC_REQUIRE_FALSE(...) (void)(0)
18395
18396 #endif
18397
18398 #define CATCH_TRANSLATE_EXCEPTION(signature)                                                       \
18399     INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(                                                     \
18400         INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
18401
18402 // "BDD-style" convenience wrappers
18403 #define SCENARIO(...)                                                                              \
18404     INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(                                                       \
18405         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____))
18406 #define SCENARIO_METHOD(className, ...)                                                            \
18407     INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(                                                \
18408         INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), className)
18409
18410 #define GIVEN(desc)
18411 #define AND_GIVEN(desc)
18412 #define WHEN(desc)
18413 #define AND_WHEN(desc)
18414 #define THEN(desc)
18415 #define AND_THEN(desc)
18416
18417 using Catch::Detail::Approx;
18418
18419 #endif
18420
18421 #endif // ! CATCH_CONFIG_IMPL_ONLY
18422
18423 // start catch_reenable_warnings.h
18424
18425 #ifdef __clang__
18426 #ifdef __ICC // icpc defines the __clang__ macro
18427 #pragma warning(pop)
18428 #else
18429 #pragma clang diagnostic pop
18430 #endif
18431 #elif defined __GNUC__
18432 #pragma GCC diagnostic pop
18433 #endif
18434
18435 // end catch_reenable_warnings.h
18436 // end catch.hpp
18437 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED