mlpack
catch.hpp
1 /*
2  * Catch v2.13.6
3  * Generated: 2021-04-16 18:23:38.044268
4  * ----------------------------------------------------------
5  * This file has been merged from multiple headers. Please don't edit it directly
6  * 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 
16 #define CATCH_VERSION_MAJOR 2
17 #define CATCH_VERSION_MINOR 13
18 #define CATCH_VERSION_PATCH 6
19 
20 #ifdef __clang__
21 # pragma clang system_header
22 #elif defined __GNUC__
23 # pragma GCC system_header
24 #endif
25 
26 // start catch_suppress_warnings.h
27 
28 #ifdef __clang__
29 # ifdef __ICC // icpc defines the __clang__ macro
30 # pragma warning(push)
31 # pragma warning(disable: 161 1682)
32 # else // __ICC
33 # pragma clang diagnostic push
34 # pragma clang diagnostic ignored "-Wpadded"
35 # pragma clang diagnostic ignored "-Wswitch-enum"
36 # pragma clang diagnostic ignored "-Wcovered-switch-default"
37 # endif
38 #elif defined __GNUC__
39  // Because REQUIREs trigger GCC's -Wparentheses, and because still
40  // supported version of g++ have only buggy support for _Pragmas,
41  // Wparentheses have to be suppressed globally.
42 # pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
43 
44 # pragma GCC diagnostic push
45 # pragma GCC diagnostic ignored "-Wunused-variable"
46 # pragma GCC diagnostic ignored "-Wpadded"
47 #endif
48 // end catch_suppress_warnings.h
49 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
50 # define CATCH_IMPL
51 # define CATCH_CONFIG_ALL_PARTS
52 #endif
53 
54 // In the impl file, we want to have access to all parts of the headers
55 // Can also be used to sanely support PCHs
56 #if defined(CATCH_CONFIG_ALL_PARTS)
57 # define CATCH_CONFIG_EXTERNAL_INTERFACES
58 # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59 # undef CATCH_CONFIG_DISABLE_MATCHERS
60 # endif
61 # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
63 # endif
64 #endif
65 
66 #if !defined(CATCH_CONFIG_IMPL_ONLY)
67 // start catch_platform.h
68 
69 // See e.g.:
70 // https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
71 #ifdef __APPLE__
72 # include <TargetConditionals.h>
73 # if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
74  (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
75 # define CATCH_PLATFORM_MAC
76 # elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
77 # define CATCH_PLATFORM_IPHONE
78 # endif
79 
80 #elif defined(linux) || defined(__linux) || defined(__linux__)
81 # define CATCH_PLATFORM_LINUX
82 
83 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
84 # define CATCH_PLATFORM_WINDOWS
85 #endif
86 
87 // end catch_platform.h
88 
89 #ifdef CATCH_IMPL
90 # ifndef CLARA_CONFIG_MAIN
91 # define CLARA_CONFIG_MAIN_NOT_DEFINED
92 # define CLARA_CONFIG_MAIN
93 # endif
94 #endif
95 
96 // start catch_user_interfaces.h
97 
98 namespace Catch {
99  unsigned int rngSeed();
100 }
101 
102 // end catch_user_interfaces.h
103 // start catch_tag_alias_autoregistrar.h
104 
105 // start catch_common.h
106 
107 // start catch_compiler_capabilities.h
108 
109 // Detect a number of compiler features - by compiler
110 // The following features are defined:
111 //
112 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
113 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
114 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
115 // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
116 // ****************
117 // Note to maintainers: if new toggles are added please document them
118 // in configuration.md, too
119 // ****************
120 
121 // In general each macro has a _NO_<feature name> form
122 // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
123 // Many features, at point of detection, define an _INTERNAL_ macro, so they
124 // can be combined, en-mass, with the _NO_ forms later.
125 
126 #ifdef __cplusplus
127 
128 # if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
129 # define CATCH_CPP14_OR_GREATER
130 # endif
131 
132 # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
133 # define CATCH_CPP17_OR_GREATER
134 # endif
135 
136 #endif
137 
138 // Only GCC compiler should be used in this block, so other compilers trying to
139 // mask themselves as GCC should be ignored.
140 #if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !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(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
166 # endif
167 
168 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
169  _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
170  _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
171 
172 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
173  _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
174 
175 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
176  _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
177 
178 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
179  _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
180 
181 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
182  _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
183 
184 #endif // __clang__
185 
187 // Assume that non-Windows platforms support posix signals by default
188 #if !defined(CATCH_PLATFORM_WINDOWS)
189  #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
190 #endif
191 
193 // We know some environments not to support full POSIX signals
194 #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
195  #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
196 #endif
197 
198 #ifdef __OS400__
199 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200 # define CATCH_CONFIG_COLOUR_NONE
201 #endif
202 
204 // Android somehow still does not support std::to_string
205 #if defined(__ANDROID__)
206 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
207 # define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
208 #endif
209 
211 // Not all Windows environments support SEH properly
212 #if defined(__MINGW32__)
213 # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
214 #endif
215 
217 // PS4
218 #if defined(__ORBIS__)
219 # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
220 #endif
221 
223 // Cygwin
224 #ifdef __CYGWIN__
225 
226 // Required for some versions of Cygwin to declare gettimeofday
227 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
228 # define _BSD_SOURCE
229 // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
230 // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
231 # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
232  && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
233 
234 # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
235 
236 # endif
237 #endif // __CYGWIN__
238 
240 // Visual C++
241 #if defined(_MSC_VER)
242 
243 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
244 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
245 
246 // Universal Windows platform does not support SEH
247 // Or console colours (or console at all...)
248 # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
249 # define CATCH_CONFIG_COLOUR_NONE
250 # else
251 # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
252 # endif
253 
254 // MSVC traditional preprocessor needs some workaround for __VA_ARGS__
255 // _MSVC_TRADITIONAL == 0 means new conformant preprocessor
256 // _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
257 # if !defined(__clang__) // Handle Clang masquerading for msvc
258 # if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
259 # define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
260 # endif // MSVC_TRADITIONAL
261 # endif // __clang__
262 
263 #endif // _MSC_VER
264 
265 #if defined(_REENTRANT) || defined(_MSC_VER)
266 // Enable async processing, as -pthread is specified or no additional linking is required
267 # define CATCH_INTERNAL_CONFIG_USE_ASYNC
268 #endif // _MSC_VER
269 
271 // Check if we are compiled with -fno-exceptions or equivalent
272 #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
273 # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
274 #endif
275 
277 // DJGPP
278 #ifdef __DJGPP__
279 # define CATCH_INTERNAL_CONFIG_NO_WCHAR
280 #endif // __DJGPP__
281 
283 // Embarcadero C++Build
284 #if defined(__BORLANDC__)
285  #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
286 #endif
287 
289 
290 // Use of __COUNTER__ is suppressed during code analysis in
291 // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
292 // handled by it.
293 // Otherwise all supported compilers support COUNTER macro,
294 // but user still might want to turn it off
295 #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
296  #define CATCH_INTERNAL_CONFIG_COUNTER
297 #endif
298 
300 
301 // RTX is a special version of Windows that is real time.
302 // This means that it is detected as Windows, but does not provide
303 // the same set of capabilities as real Windows does.
304 #if defined(UNDER_RTSS) || defined(RTX64_BUILD)
305  #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
306  #define CATCH_INTERNAL_CONFIG_NO_ASYNC
307  #define CATCH_CONFIG_COLOUR_NONE
308 #endif
309 
310 #if !defined(_GLIBCXX_USE_C99_MATH_TR1)
311 #define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
312 #endif
313 
314 // Various stdlib support checks that require __has_include
315 #if defined(__has_include)
316  // Check if string_view is available and usable
317  #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
318  # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
319  #endif
320 
321  // Check if optional is available and usable
322  # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
323  # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
324  # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
325 
326  // Check if byte is available and usable
327  # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
328  # include <cstddef>
329  # if __cpp_lib_byte > 0
330  # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
331  # endif
332  # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
333 
334  // Check if variant is available and usable
335  # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
336  # if defined(__clang__) && (__clang_major__ < 8)
337  // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
338  // fix should be in clang 8, workaround in libstdc++ 8.2
339  # include <ciso646>
340  # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
341  # define CATCH_CONFIG_NO_CPP17_VARIANT
342  # else
343  # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
344  # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
345  # else
346  # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
347  # endif // defined(__clang__) && (__clang_major__ < 8)
348  # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
349 #endif // defined(__has_include)
350 
351 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
352 # define CATCH_CONFIG_COUNTER
353 #endif
354 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
355 # define CATCH_CONFIG_WINDOWS_SEH
356 #endif
357 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
358 #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
359 # define CATCH_CONFIG_POSIX_SIGNALS
360 #endif
361 // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
362 #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
363 # define CATCH_CONFIG_WCHAR
364 #endif
365 
366 #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
367 # define CATCH_CONFIG_CPP11_TO_STRING
368 #endif
369 
370 #if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
371 # define CATCH_CONFIG_CPP17_OPTIONAL
372 #endif
373 
374 #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
375 # define CATCH_CONFIG_CPP17_STRING_VIEW
376 #endif
377 
378 #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
379 # define CATCH_CONFIG_CPP17_VARIANT
380 #endif
381 
382 #if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
383 # define CATCH_CONFIG_CPP17_BYTE
384 #endif
385 
386 #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
387 # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
388 #endif
389 
390 #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
391 # define CATCH_CONFIG_NEW_CAPTURE
392 #endif
393 
394 #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
395 # define CATCH_CONFIG_DISABLE_EXCEPTIONS
396 #endif
397 
398 #if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
399 # define CATCH_CONFIG_POLYFILL_ISNAN
400 #endif
401 
402 #if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
403 # define CATCH_CONFIG_USE_ASYNC
404 #endif
405 
406 #if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
407 # define CATCH_CONFIG_ANDROID_LOGWRITE
408 #endif
409 
410 #if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
411 # define CATCH_CONFIG_GLOBAL_NEXTAFTER
412 #endif
413 
414 // Even if we do not think the compiler has that warning, we still have
415 // to provide a macro that can be used by the code.
416 #if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
417 # define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
418 #endif
419 #if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
420 # define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
421 #endif
422 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
423 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
424 #endif
425 #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
426 # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
427 #endif
428 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
429 # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
430 #endif
431 #if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
432 # define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
433 #endif
434 
435 // The goal of this macro is to avoid evaluation of the arguments, but
436 // still have the compiler warn on problems inside...
437 #if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
438 # define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
439 #endif
440 
441 #if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
442 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
443 #elif defined(__clang__) && (__clang_major__ < 5)
444 # undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
445 #endif
446 
447 #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
448 # define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
449 #endif
450 
451 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
452 #define CATCH_TRY if ((true))
453 #define CATCH_CATCH_ALL if ((false))
454 #define CATCH_CATCH_ANON(type) if ((false))
455 #else
456 #define CATCH_TRY try
457 #define CATCH_CATCH_ALL catch (...)
458 #define CATCH_CATCH_ANON(type) catch (type)
459 #endif
460 
461 #if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
462 #define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
463 #endif
464 
465 // end catch_compiler_capabilities.h
466 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
467 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
468 #ifdef CATCH_CONFIG_COUNTER
469 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
470 #else
471 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
472 #endif
473 
474 #include <iosfwd>
475 #include <string>
476 #include <cstdint>
477 
478 // We need a dummy global operator<< so we can bring it into Catch namespace later
480 std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
481 
482 namespace Catch {
483 
484  struct CaseSensitive { enum Choice {
485  Yes,
486  No
487  }; };
488 
489  class NonCopyable {
490  NonCopyable( NonCopyable const& ) = delete;
491  NonCopyable( NonCopyable && ) = delete;
492  NonCopyable& operator = ( NonCopyable const& ) = delete;
493  NonCopyable& operator = ( NonCopyable && ) = delete;
494 
495  protected:
496  NonCopyable();
497  virtual ~NonCopyable();
498  };
499 
500  struct SourceLineInfo {
501 
502  SourceLineInfo() = delete;
503  SourceLineInfo( char const* _file, std::size_t _line ) noexcept
504  : file( _file ),
505  line( _line )
506  {}
507 
508  SourceLineInfo( SourceLineInfo const& other ) = default;
509  SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
510  SourceLineInfo( SourceLineInfo&& ) noexcept = default;
511  SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
512 
513  bool empty() const noexcept { return file[0] == '\0'; }
514  bool operator == ( SourceLineInfo const& other ) const noexcept;
515  bool operator < ( SourceLineInfo const& other ) const noexcept;
516 
517  char const* file;
518  std::size_t line;
519  };
520 
521  std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
522 
523  // Bring in operator<< from global namespace into Catch namespace
524  // This is necessary because the overload of operator<< above makes
525  // lookup stop at namespace Catch
526  using ::operator<<;
527 
528  // Use this in variadic streaming macros to allow
529  // >> +StreamEndStop
530  // as well as
531  // >> stuff +StreamEndStop
532  struct StreamEndStop {
533  std::string operator+() const;
534  };
535  template<typename T>
536  T const& operator + ( T const& value, StreamEndStop ) {
537  return value;
538  }
539 }
540 
541 #define CATCH_INTERNAL_LINEINFO \
542  ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
543 
544 // end catch_common.h
545 namespace Catch {
546 
548  RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
549  };
550 
551 } // end namespace Catch
552 
553 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
554  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
555  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
556  namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
557  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
558 
559 // end catch_tag_alias_autoregistrar.h
560 // start catch_test_registry.h
561 
562 // start catch_interfaces_testcase.h
563 
564 #include <vector>
565 
566 namespace Catch {
567 
568  class TestSpec;
569 
570  struct ITestInvoker {
571  virtual void invoke () const = 0;
572  virtual ~ITestInvoker();
573  };
574 
575  class TestCase;
576  struct IConfig;
577 
579  virtual ~ITestCaseRegistry();
580  virtual std::vector<TestCase> const& getAllTests() const = 0;
581  virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
582  };
583 
584  bool isThrowSafe( TestCase const& testCase, IConfig const& config );
585  bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
586  std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
587  std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
588 
589 }
590 
591 // end catch_interfaces_testcase.h
592 // start catch_stringref.h
593 
594 #include <cstddef>
595 #include <string>
596 #include <iosfwd>
597 #include <cassert>
598 
599 namespace Catch {
600 
604  class StringRef {
605  public:
606  using size_type = std::size_t;
607  using const_iterator = const char*;
608 
609  private:
610  static constexpr char const* const s_empty = "";
611 
612  char const* m_start = s_empty;
613  size_type m_size = 0;
614 
615  public: // construction
616  constexpr StringRef() noexcept = default;
617 
618  StringRef( char const* rawChars ) noexcept;
619 
620  constexpr StringRef( char const* rawChars, size_type size ) noexcept
621  : m_start( rawChars ),
622  m_size( size )
623  {}
624 
625  StringRef( std::string const& stdString ) noexcept
626  : m_start( stdString.c_str() ),
627  m_size( stdString.size() )
628  {}
629 
630  explicit operator std::string() const {
631  return std::string(m_start, m_size);
632  }
633 
634  public: // operators
635  auto operator == ( StringRef const& other ) const noexcept -> bool;
636  auto operator != (StringRef const& other) const noexcept -> bool {
637  return !(*this == other);
638  }
639 
640  auto operator[] ( size_type index ) const noexcept -> char {
641  assert(index < m_size);
642  return m_start[index];
643  }
644 
645  public: // named queries
646  constexpr auto empty() const noexcept -> bool {
647  return m_size == 0;
648  }
649  constexpr auto size() const noexcept -> size_type {
650  return m_size;
651  }
652 
653  // Returns the current start pointer. If the StringRef is not
654  // null-terminated, throws std::domain_exception
655  auto c_str() const -> char const*;
656 
657  public: // substrings and searches
658  // Returns a substring of [start, start + length).
659  // If start + length > size(), then the substring is [start, size()).
660  // If start > size(), then the substring is empty.
661  auto substr( size_type start, size_type length ) const noexcept -> StringRef;
662 
663  // Returns the current start pointer. May not be null-terminated.
664  auto data() const noexcept -> char const*;
665 
666  constexpr auto isNullTerminated() const noexcept -> bool {
667  return m_start[m_size] == '\0';
668  }
669 
670  public: // iterators
671  constexpr const_iterator begin() const { return m_start; }
672  constexpr const_iterator end() const { return m_start + m_size; }
673  };
674 
675  auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
676  auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
677 
678  constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
679  return StringRef( rawChars, size );
680  }
681 } // namespace Catch
682 
683 constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
684  return Catch::StringRef( rawChars, size );
685 }
686 
687 // end catch_stringref.h
688 // start catch_preprocessor.hpp
689 
690 
691 #define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
692 #define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
693 #define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
694 #define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
695 #define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
696 #define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
697 
698 #ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
699 #define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
700 // MSVC needs more evaluations
701 #define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
702 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
703 #else
704 #define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
705 #endif
706 
707 #define CATCH_REC_END(...)
708 #define CATCH_REC_OUT
709 
710 #define CATCH_EMPTY()
711 #define CATCH_DEFER(id) id CATCH_EMPTY()
712 
713 #define CATCH_REC_GET_END2() 0, CATCH_REC_END
714 #define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
715 #define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
716 #define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
717 #define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
718 #define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
719 
720 #define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
721 #define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
722 #define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
723 
724 #define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
725 #define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
726 #define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
727 
728 // Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
729 // and passes userdata as the first parameter to each invocation,
730 // e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
731 #define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
732 
733 #define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
734 
735 #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
736 #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
737 #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
738 #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
739 #define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
740 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
741 #define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
742 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
743 #else
744 // MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
745 #define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
746 #define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
747 #define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
748 #endif
749 
750 #define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
751 #define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
752 
753 #define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
754 
755 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
756 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
757 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
758 #else
759 #define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
760 #define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
761 #endif
762 
763 #define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
764  CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
765 
766 #define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
767 #define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
768 #define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
769 #define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
770 #define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
771 #define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
772 #define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
773 #define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
774 #define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
775 #define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
776 #define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
777 
778 #define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
779 
780 #define INTERNAL_CATCH_TYPE_GEN\
781  template<typename...> struct TypeList {};\
782  template<typename...Ts>\
783  constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
784  template<template<typename...> class...> struct TemplateTypeList{};\
785  template<template<typename...> class...Cs>\
786  constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
787  template<typename...>\
788  struct append;\
789  template<typename...>\
790  struct rewrap;\
791  template<template<typename...> class, typename...>\
792  struct create;\
793  template<template<typename...> class, typename>\
794  struct convert;\
795  \
796  template<typename T> \
797  struct append<T> { using type = T; };\
798  template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
799  struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
800  template< template<typename...> class L1, typename...E1, typename...Rest>\
801  struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
802  \
803  template< template<typename...> class Container, template<typename...> class List, typename...elems>\
804  struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
805  template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
806  struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
807  \
808  template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
809  struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
810  template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
811  struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
812 
813 #define INTERNAL_CATCH_NTTP_1(signature, ...)\
814  template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
815  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
816  constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
817  template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
818  template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
819  constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
820  \
821  template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
822  struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
823  template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
824  struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
825  template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
826  struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
827 
828 #define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
829 #define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
830  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
831  static void TestName()
832 #define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
833  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834  static void TestName()
835 
836 #define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
837 #define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
838  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
839  static void TestName()
840 #define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
841  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
842  static void TestName()
843 
844 #define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
845  template<typename Type>\
846  void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
847  {\
848  Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
849  }
850 
851 #define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
852  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
853  void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
854  {\
855  Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
856  }
857 
858 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
859  template<typename Type>\
860  void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
861  {\
862  Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
863  }
864 
865 #define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
866  template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
867  void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
868  {\
869  Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
870  }
871 
872 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
873 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
874  template<typename TestType> \
875  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
876  void test();\
877  }
878 
879 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
880  template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
881  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
882  void test();\
883  }
884 
885 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
886 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
887  template<typename TestType> \
888  void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
889 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
890  template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
891  void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
892 
893 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
894 #define INTERNAL_CATCH_NTTP_0
895 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
896 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
897 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
898 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
899 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
900 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
901 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
902 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
903 #else
904 #define INTERNAL_CATCH_NTTP_0(signature)
905 #define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
906 #define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
907 #define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
908 #define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
909 #define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
910 #define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
911 #define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
912 #define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
913 #endif
914 
915 // end catch_preprocessor.hpp
916 // start catch_meta.hpp
917 
918 
919 #include <type_traits>
920 
921 namespace Catch {
922  template<typename T>
923  struct always_false : std::false_type {};
924 
925  template <typename> struct true_given : std::true_type {};
927  template <typename Fun, typename... Args>
928  true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
929  template <typename...>
930  std::false_type static test(...);
931  };
932 
933  template <typename T>
934  struct is_callable;
935 
936  template <typename Fun, typename... Args>
937  struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
938 
939 #if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
940  // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
941  // replaced with std::invoke_result here.
942  template <typename Func, typename... U>
943  using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
944 #else
945  // Keep ::type here because we still support C++11
946  template <typename Func, typename... U>
947  using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
948 #endif
949 
950 } // namespace Catch
951 
952 namespace mpl_{
953  struct na;
954 }
955 
956 // end catch_meta.hpp
957 namespace Catch {
958 
959 template<typename C>
961  void (C::*m_testAsMethod)();
962 public:
963  TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
964 
965  void invoke() const override {
966  C obj;
967  (obj.*m_testAsMethod)();
968  }
969 };
970 
971 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
972 
973 template<typename C>
974 auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
975  return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
976 }
977 
978 struct NameAndTags {
979  NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
980  StringRef name;
981  StringRef tags;
982 };
983 
985  AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
986  ~AutoReg();
987 };
988 
989 } // end namespace Catch
990 
991 #if defined(CATCH_CONFIG_DISABLE)
992  #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
993  static void TestName()
994  #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
995  namespace{ \
996  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
997  void test(); \
998  }; \
999  } \
1000  void TestName::test()
1001  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1002  INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1003  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1004  namespace{ \
1005  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1006  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1007  } \
1008  } \
1009  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1010 
1011  #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1012  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1013  INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1014  #else
1015  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1017  #endif
1018 
1019  #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1020  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1021  INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1022  #else
1023  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1025  #endif
1026 
1027  #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1028  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1029  INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1030  #else
1031  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1033  #endif
1034 
1035  #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1036  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1037  INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1038  #else
1039  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1041  #endif
1042 #endif
1043 
1045  #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1046  static void TestName(); \
1047  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1048  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1049  namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1050  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1051  static void TestName()
1052  #define INTERNAL_CATCH_TESTCASE( ... ) \
1053  INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
1054 
1056  #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1057  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1058  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1059  namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1060  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1061 
1063  #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1064  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1065  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1066  namespace{ \
1067  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1068  void test(); \
1069  }; \
1070  Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1071  } \
1072  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1073  void TestName::test()
1074  #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1075  INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1076 
1078  #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1079  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1080  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1081  Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1082  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1083 
1085  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1086  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1087  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1088  CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1089  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1090  INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1091  namespace {\
1092  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1093  INTERNAL_CATCH_TYPE_GEN\
1094  INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1095  INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1096  template<typename...Types> \
1097  struct TestName{\
1098  TestName(){\
1099  int index = 0; \
1100  constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1101  using expander = int[];\
1102  (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1103  }\
1104  };\
1105  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1106  TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1107  return 0;\
1108  }();\
1109  }\
1110  }\
1111  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1112  INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1113 
1114 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1115  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1116  INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ )
1117 #else
1118  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1120 #endif
1121 
1122 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1123  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1124  INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ )
1125 #else
1126  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1128 #endif
1129 
1130  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1131  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1132  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1133  CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1134  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1135  template<typename TestType> static void TestFuncName(); \
1136  namespace {\
1137  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1138  INTERNAL_CATCH_TYPE_GEN \
1139  INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1140  template<typename... Types> \
1141  struct TestName { \
1142  void reg_tests() { \
1143  int index = 0; \
1144  using expander = int[]; \
1145  constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1146  constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1147  constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1148  (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
1149  } \
1150  }; \
1151  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1152  using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1153  TestInit t; \
1154  t.reg_tests(); \
1155  return 0; \
1156  }(); \
1157  } \
1158  } \
1159  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1160  template<typename TestType> \
1161  static void TestFuncName()
1162 
1163 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1164  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1165  INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T,__VA_ARGS__)
1166 #else
1167  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, typename T, __VA_ARGS__ ) )
1169 #endif
1170 
1171 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1172  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1173  INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__)
1174 #else
1175  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, Signature, __VA_ARGS__ ) )
1177 #endif
1178 
1179  #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1180  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1181  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1182  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1183  template<typename TestType> static void TestFunc(); \
1184  namespace {\
1185  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1186  INTERNAL_CATCH_TYPE_GEN\
1187  template<typename... Types> \
1188  struct TestName { \
1189  void reg_tests() { \
1190  int index = 0; \
1191  using expander = int[]; \
1192  (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
1193  } \
1194  };\
1195  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1196  using TestInit = typename convert<TestName, TmplList>::type; \
1197  TestInit t; \
1198  t.reg_tests(); \
1199  return 0; \
1200  }(); \
1201  }}\
1202  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1203  template<typename TestType> \
1204  static void TestFunc()
1205 
1206  #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1207  INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, TmplList )
1208 
1209  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1210  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1211  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1212  CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1213  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1214  namespace {\
1215  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1216  INTERNAL_CATCH_TYPE_GEN\
1217  INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1218  INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1219  INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1220  template<typename...Types> \
1221  struct TestNameClass{\
1222  TestNameClass(){\
1223  int index = 0; \
1224  constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1225  using expander = int[];\
1226  (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1227  }\
1228  };\
1229  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1230  TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1231  return 0;\
1232  }();\
1233  }\
1234  }\
1235  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1236  INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1237 
1238 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1239  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1240  INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1241 #else
1242  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1244 #endif
1245 
1246 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1247  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1248  INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1249 #else
1250  #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1252 #endif
1253 
1254  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1255  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1256  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1257  CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1258  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1259  template<typename TestType> \
1260  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1261  void test();\
1262  };\
1263  namespace {\
1264  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1265  INTERNAL_CATCH_TYPE_GEN \
1266  INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1267  template<typename...Types>\
1268  struct TestNameClass{\
1269  void reg_tests(){\
1270  int index = 0;\
1271  using expander = int[];\
1272  constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1273  constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1274  constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1275  (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
1276  }\
1277  };\
1278  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1279  using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1280  TestInit t;\
1281  t.reg_tests();\
1282  return 0;\
1283  }(); \
1284  }\
1285  }\
1286  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1287  template<typename TestType> \
1288  void TestName<TestType>::test()
1289 
1290 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1291  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1292  INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1293 #else
1294  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1296 #endif
1297 
1298 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1299  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1300  INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1301 #else
1302  #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303  INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1304 #endif
1305 
1306  #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1307  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1308  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1309  CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1310  template<typename TestType> \
1311  struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1312  void test();\
1313  };\
1314  namespace {\
1315  namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1316  INTERNAL_CATCH_TYPE_GEN\
1317  template<typename...Types>\
1318  struct TestNameClass{\
1319  void reg_tests(){\
1320  int index = 0;\
1321  using expander = int[];\
1322  (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
1323  }\
1324  };\
1325  static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1326  using TestInit = typename convert<TestNameClass, TmplList>::type;\
1327  TestInit t;\
1328  t.reg_tests();\
1329  return 0;\
1330  }(); \
1331  }}\
1332  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1333  template<typename TestType> \
1334  void TestName<TestType>::test()
1335 
1336 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1337  INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, TmplList )
1338 
1339 // end catch_test_registry.h
1340 // start catch_capture.hpp
1341 
1342 // start catch_assertionhandler.h
1343 
1344 // start catch_assertioninfo.h
1345 
1346 // start catch_result_type.h
1347 
1348 namespace Catch {
1349 
1350  // ResultWas::OfType enum
1351  struct ResultWas { enum OfType {
1352  Unknown = -1,
1353  Ok = 0,
1354  Info = 1,
1355  Warning = 2,
1356 
1357  FailureBit = 0x10,
1358 
1359  ExpressionFailed = FailureBit | 1,
1360  ExplicitFailure = FailureBit | 2,
1361 
1362  Exception = 0x100 | FailureBit,
1363 
1364  ThrewException = Exception | 1,
1365  DidntThrowException = Exception | 2,
1366 
1367  FatalErrorCondition = 0x200 | FailureBit
1368 
1369  }; };
1370 
1371  bool isOk( ResultWas::OfType resultType );
1372  bool isJustInfo( int flags );
1373 
1374  // ResultDisposition::Flags enum
1375  struct ResultDisposition { enum Flags {
1376  Normal = 0x01,
1377 
1378  ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1379  FalseTest = 0x04, // Prefix expression with !
1380  SuppressFail = 0x08 // Failures are reported but do not fail the test
1381  }; };
1382 
1383  ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1384 
1385  bool shouldContinueOnFailure( int flags );
1386  inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1387  bool shouldSuppressFailure( int flags );
1388 
1389 } // end namespace Catch
1390 
1391 // end catch_result_type.h
1392 namespace Catch {
1393 
1395  {
1396  StringRef macroName;
1397  SourceLineInfo lineInfo;
1398  StringRef capturedExpression;
1399  ResultDisposition::Flags resultDisposition;
1400 
1401  // We want to delete this constructor but a compiler bug in 4.8 means
1402  // the struct is then treated as non-aggregate
1403  //AssertionInfo() = delete;
1404  };
1405 
1406 } // end namespace Catch
1407 
1408 // end catch_assertioninfo.h
1409 // start catch_decomposer.h
1410 
1411 // start catch_tostring.h
1412 
1413 #include <vector>
1414 #include <cstddef>
1415 #include <type_traits>
1416 #include <string>
1417 // start catch_stream.h
1418 
1419 #include <iosfwd>
1420 #include <cstddef>
1421 #include <ostream>
1422 
1423 namespace Catch {
1424 
1425  std::ostream& cout();
1426  std::ostream& cerr();
1427  std::ostream& clog();
1428 
1429  class StringRef;
1430 
1431  struct IStream {
1432  virtual ~IStream();
1433  virtual std::ostream& stream() const = 0;
1434  };
1435 
1436  auto makeStream( StringRef const &filename ) -> IStream const*;
1437 
1439  std::size_t m_index;
1440  std::ostream* m_oss;
1441  public:
1444 
1445  auto str() const -> std::string;
1446 
1447  template<typename T>
1448  auto operator << ( T const& value ) -> ReusableStringStream& {
1449  *m_oss << value;
1450  return *this;
1451  }
1452  auto get() -> std::ostream& { return *m_oss; }
1453  };
1454 }
1455 
1456 // end catch_stream.h
1457 // start catch_interfaces_enum_values_registry.h
1458 
1459 #include <vector>
1460 
1461 namespace Catch {
1462 
1463  namespace Detail {
1464  struct EnumInfo {
1465  StringRef m_name;
1466  std::vector<std::pair<int, StringRef>> m_values;
1467 
1468  ~EnumInfo();
1469 
1470  StringRef lookup( int value ) const;
1471  };
1472  } // namespace Detail
1473 
1475  virtual ~IMutableEnumValuesRegistry();
1476 
1477  virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1478 
1479  template<typename E>
1480  Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1481  static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1482  std::vector<int> intValues;
1483  intValues.reserve( values.size() );
1484  for( auto enumValue : values )
1485  intValues.push_back( static_cast<int>( enumValue ) );
1486  return registerEnum( enumName, allEnums, intValues );
1487  }
1488  };
1489 
1490 } // Catch
1491 
1492 // end catch_interfaces_enum_values_registry.h
1493 
1494 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1495 #include <string_view>
1496 #endif
1497 
1498 #ifdef __OBJC__
1499 // start catch_objc_arc.hpp
1500 
1501 #import <Foundation/Foundation.h>
1502 
1503 #ifdef __has_feature
1504 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1505 #else
1506 #define CATCH_ARC_ENABLED 0
1507 #endif
1508 
1509 void arcSafeRelease( NSObject* obj );
1510 id performOptionalSelector( id obj, SEL sel );
1511 
1512 #if !CATCH_ARC_ENABLED
1513 inline void arcSafeRelease( NSObject* obj ) {
1514  [obj release];
1515 }
1516 inline id performOptionalSelector( id obj, SEL sel ) {
1517  if( [obj respondsToSelector: sel] )
1518  return [obj performSelector: sel];
1519  return nil;
1520 }
1521 #define CATCH_UNSAFE_UNRETAINED
1522 #define CATCH_ARC_STRONG
1523 #else
1524 inline void arcSafeRelease( NSObject* ){}
1525 inline id performOptionalSelector( id obj, SEL sel ) {
1526 #ifdef __clang__
1527 #pragma clang diagnostic push
1528 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1529 #endif
1530  if( [obj respondsToSelector: sel] )
1531  return [obj performSelector: sel];
1532 #ifdef __clang__
1533 #pragma clang diagnostic pop
1534 #endif
1535  return nil;
1536 }
1537 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1538 #define CATCH_ARC_STRONG __strong
1539 #endif
1540 
1541 // end catch_objc_arc.hpp
1542 #endif
1543 
1544 #ifdef _MSC_VER
1545 #pragma warning(push)
1546 #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1547 #endif
1548 
1549 namespace Catch {
1550  namespace Detail {
1551 
1552  extern const std::string unprintableString;
1553 
1554  std::string rawMemoryToString( const void *object, std::size_t size );
1555 
1556  template<typename T>
1557  std::string rawMemoryToString( const T& object ) {
1558  return rawMemoryToString( &object, sizeof(object) );
1559  }
1560 
1561  template<typename T>
1563  template<typename Stream, typename U>
1564  static auto test(int)
1565  -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1566 
1567  template<typename, typename>
1568  static auto test(...)->std::false_type;
1569 
1570  public:
1571  static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1572  };
1573 
1574  template<typename E>
1575  std::string convertUnknownEnumToString( E e );
1576 
1577  template<typename T>
1578  typename std::enable_if<
1579  !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1580  std::string>::type convertUnstreamable( T const& ) {
1581  return Detail::unprintableString;
1582  }
1583  template<typename T>
1584  typename std::enable_if<
1585  !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1586  std::string>::type convertUnstreamable(T const& ex) {
1587  return ex.what();
1588  }
1589 
1590  template<typename T>
1591  typename std::enable_if<
1592  std::is_enum<T>::value
1593  , std::string>::type convertUnstreamable( T const& value ) {
1594  return convertUnknownEnumToString( value );
1595  }
1596 
1597 #if defined(_MANAGED)
1598  template<typename T>
1600  std::string clrReferenceToString( T^ ref ) {
1601  if (ref == nullptr)
1602  return std::string("null");
1603  auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1604  cli::pin_ptr<System::Byte> p = &bytes[0];
1605  return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1606  }
1607 #endif
1608 
1609  } // namespace Detail
1610 
1611  // If we decide for C++14, change these to enable_if_ts
1612  template <typename T, typename = void>
1613  struct StringMaker {
1614  template <typename Fake = T>
1615  static
1616  typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1617  convert(const Fake& value) {
1619  // NB: call using the function-like syntax to avoid ambiguity with
1620  // user-defined templated operator<< under clang.
1621  rss.operator<<(value);
1622  return rss.str();
1623  }
1624 
1625  template <typename Fake = T>
1626  static
1627  typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1628  convert( const Fake& value ) {
1629 #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1630  return Detail::convertUnstreamable(value);
1631 #else
1632  return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1633 #endif
1634  }
1635  };
1636 
1637  namespace Detail {
1638 
1639  // This function dispatches all stringification requests inside of Catch.
1640  // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1641  template <typename T>
1642  std::string stringify(const T& e) {
1643  return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1644  }
1645 
1646  template<typename E>
1647  std::string convertUnknownEnumToString( E e ) {
1648  return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1649  }
1650 
1651 #if defined(_MANAGED)
1652  template <typename T>
1653  std::string stringify( T^ e ) {
1654  return ::Catch::StringMaker<T^>::convert(e);
1655  }
1656 #endif
1657 
1658  } // namespace Detail
1659 
1660  // Some predefined specializations
1661 
1662  template<>
1663  struct StringMaker<std::string> {
1664  static std::string convert(const std::string& str);
1665  };
1666 
1667 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1668  template<>
1669  struct StringMaker<std::string_view> {
1670  static std::string convert(std::string_view str);
1671  };
1672 #endif
1673 
1674  template<>
1675  struct StringMaker<char const *> {
1676  static std::string convert(char const * str);
1677  };
1678  template<>
1679  struct StringMaker<char *> {
1680  static std::string convert(char * str);
1681  };
1682 
1683 #ifdef CATCH_CONFIG_WCHAR
1684  template<>
1685  struct StringMaker<std::wstring> {
1686  static std::string convert(const std::wstring& wstr);
1687  };
1688 
1689 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1690  template<>
1691  struct StringMaker<std::wstring_view> {
1692  static std::string convert(std::wstring_view str);
1693  };
1694 # endif
1695 
1696  template<>
1697  struct StringMaker<wchar_t const *> {
1698  static std::string convert(wchar_t const * str);
1699  };
1700  template<>
1701  struct StringMaker<wchar_t *> {
1702  static std::string convert(wchar_t * str);
1703  };
1704 #endif
1705 
1706  // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1707  // while keeping string semantics?
1708  template<int SZ>
1709  struct StringMaker<char[SZ]> {
1710  static std::string convert(char const* str) {
1711  return ::Catch::Detail::stringify(std::string{ str });
1712  }
1713  };
1714  template<int SZ>
1715  struct StringMaker<signed char[SZ]> {
1716  static std::string convert(signed char const* str) {
1717  return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1718  }
1719  };
1720  template<int SZ>
1721  struct StringMaker<unsigned char[SZ]> {
1722  static std::string convert(unsigned char const* str) {
1723  return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1724  }
1725  };
1726 
1727 #if defined(CATCH_CONFIG_CPP17_BYTE)
1728  template<>
1729  struct StringMaker<std::byte> {
1730  static std::string convert(std::byte value);
1731  };
1732 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
1733  template<>
1734  struct StringMaker<int> {
1735  static std::string convert(int value);
1736  };
1737  template<>
1738  struct StringMaker<long> {
1739  static std::string convert(long value);
1740  };
1741  template<>
1742  struct StringMaker<long long> {
1743  static std::string convert(long long value);
1744  };
1745  template<>
1746  struct StringMaker<unsigned int> {
1747  static std::string convert(unsigned int value);
1748  };
1749  template<>
1750  struct StringMaker<unsigned long> {
1751  static std::string convert(unsigned long value);
1752  };
1753  template<>
1754  struct StringMaker<unsigned long long> {
1755  static std::string convert(unsigned long long value);
1756  };
1757 
1758  template<>
1759  struct StringMaker<bool> {
1760  static std::string convert(bool b);
1761  };
1762 
1763  template<>
1764  struct StringMaker<char> {
1765  static std::string convert(char c);
1766  };
1767  template<>
1768  struct StringMaker<signed char> {
1769  static std::string convert(signed char c);
1770  };
1771  template<>
1772  struct StringMaker<unsigned char> {
1773  static std::string convert(unsigned char c);
1774  };
1775 
1776  template<>
1777  struct StringMaker<std::nullptr_t> {
1778  static std::string convert(std::nullptr_t);
1779  };
1780 
1781  template<>
1782  struct StringMaker<float> {
1783  static std::string convert(float value);
1784  static int precision;
1785  };
1786 
1787  template<>
1788  struct StringMaker<double> {
1789  static std::string convert(double value);
1790  static int precision;
1791  };
1792 
1793  template <typename T>
1794  struct StringMaker<T*> {
1795  template <typename U>
1796  static std::string convert(U* p) {
1797  if (p) {
1798  return ::Catch::Detail::rawMemoryToString(p);
1799  } else {
1800  return "nullptr";
1801  }
1802  }
1803  };
1804 
1805  template <typename R, typename C>
1806  struct StringMaker<R C::*> {
1807  static std::string convert(R C::* p) {
1808  if (p) {
1809  return ::Catch::Detail::rawMemoryToString(p);
1810  } else {
1811  return "nullptr";
1812  }
1813  }
1814  };
1815 
1816 #if defined(_MANAGED)
1817  template <typename T>
1818  struct StringMaker<T^> {
1819  static std::string convert( T^ ref ) {
1820  return ::Catch::Detail::clrReferenceToString(ref);
1821  }
1822  };
1823 #endif
1824 
1825  namespace Detail {
1826  template<typename InputIterator, typename Sentinel = InputIterator>
1827  std::string rangeToString(InputIterator first, Sentinel last) {
1829  rss << "{ ";
1830  if (first != last) {
1831  rss << ::Catch::Detail::stringify(*first);
1832  for (++first; first != last; ++first)
1833  rss << ", " << ::Catch::Detail::stringify(*first);
1834  }
1835  rss << " }";
1836  return rss.str();
1837  }
1838  }
1839 
1840 #ifdef __OBJC__
1841  template<>
1842  struct StringMaker<NSString*> {
1843  static std::string convert(NSString * nsstring) {
1844  if (!nsstring)
1845  return "nil";
1846  return std::string("@") + [nsstring UTF8String];
1847  }
1848  };
1849  template<>
1850  struct StringMaker<NSObject*> {
1851  static std::string convert(NSObject* nsObject) {
1852  return ::Catch::Detail::stringify([nsObject description]);
1853  }
1854 
1855  };
1856  namespace Detail {
1857  inline std::string stringify( NSString* nsstring ) {
1858  return StringMaker<NSString*>::convert( nsstring );
1859  }
1860 
1861  } // namespace Detail
1862 #endif // __OBJC__
1863 
1864 } // namespace Catch
1865 
1867 // Separate std-lib types stringification, so it can be selectively enabled
1868 // This means that we do not bring in
1869 
1870 #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1871 # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1872 # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1873 # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1874 # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1875 # define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1876 #endif
1877 
1878 // Separate std::pair specialization
1879 #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1880 #include <utility>
1881 namespace Catch {
1882  template<typename T1, typename T2>
1883  struct StringMaker<std::pair<T1, T2> > {
1884  static std::string convert(const std::pair<T1, T2>& pair) {
1886  rss << "{ "
1887  << ::Catch::Detail::stringify(pair.first)
1888  << ", "
1889  << ::Catch::Detail::stringify(pair.second)
1890  << " }";
1891  return rss.str();
1892  }
1893  };
1894 }
1895 #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1896 
1897 #if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1898 #include <optional>
1899 namespace Catch {
1900  template<typename T>
1901  struct StringMaker<std::optional<T> > {
1902  static std::string convert(const std::optional<T>& optional) {
1904  if (optional.has_value()) {
1905  rss << ::Catch::Detail::stringify(*optional);
1906  } else {
1907  rss << "{ }";
1908  }
1909  return rss.str();
1910  }
1911  };
1912 }
1913 #endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1914 
1915 // Separate std::tuple specialization
1916 #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1917 #include <tuple>
1918 namespace Catch {
1919  namespace Detail {
1920  template<
1921  typename Tuple,
1922  std::size_t N = 0,
1923  bool = (N < std::tuple_size<Tuple>::value)
1924  >
1925  struct TupleElementPrinter {
1926  static void print(const Tuple& tuple, std::ostream& os) {
1927  os << (N ? ", " : " ")
1928  << ::Catch::Detail::stringify(std::get<N>(tuple));
1929  TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1930  }
1931  };
1932 
1933  template<
1934  typename Tuple,
1935  std::size_t N
1936  >
1937  struct TupleElementPrinter<Tuple, N, false> {
1938  static void print(const Tuple&, std::ostream&) {}
1939  };
1940 
1941  }
1942 
1943  template<typename ...Types>
1944  struct StringMaker<std::tuple<Types...>> {
1945  static std::string convert(const std::tuple<Types...>& tuple) {
1947  rss << '{';
1948  Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1949  rss << " }";
1950  return rss.str();
1951  }
1952  };
1953 }
1954 #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1955 
1956 #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1957 #include <variant>
1958 namespace Catch {
1959  template<>
1960  struct StringMaker<std::monostate> {
1961  static std::string convert(const std::monostate&) {
1962  return "{ }";
1963  }
1964  };
1965 
1966  template<typename... Elements>
1967  struct StringMaker<std::variant<Elements...>> {
1968  static std::string convert(const std::variant<Elements...>& variant) {
1969  if (variant.valueless_by_exception()) {
1970  return "{valueless variant}";
1971  } else {
1972  return std::visit(
1973  [](const auto& value) {
1974  return ::Catch::Detail::stringify(value);
1975  },
1976  variant
1977  );
1978  }
1979  }
1980  };
1981 }
1982 #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1983 
1984 namespace Catch {
1985  // Import begin/ end from std here
1986  using std::begin;
1987  using std::end;
1988 
1989  namespace detail {
1990  template <typename...>
1991  struct void_type {
1992  using type = void;
1993  };
1994 
1995  template <typename T, typename = void>
1996  struct is_range_impl : std::false_type {
1997  };
1998 
1999  template <typename T>
2001  };
2002  } // namespace detail
2003 
2004  template <typename T>
2006  };
2007 
2008 #if defined(_MANAGED) // Managed types are never ranges
2009  template <typename T>
2010  struct is_range<T^> {
2011  static const bool value = false;
2012  };
2013 #endif
2014 
2015  template<typename Range>
2016  std::string rangeToString( Range const& range ) {
2017  return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2018  }
2019 
2020  // Handle vector<bool> specially
2021  template<typename Allocator>
2022  std::string rangeToString( std::vector<bool, Allocator> const& v ) {
2024  rss << "{ ";
2025  bool first = true;
2026  for( bool b : v ) {
2027  if( first )
2028  first = false;
2029  else
2030  rss << ", ";
2031  rss << ::Catch::Detail::stringify( b );
2032  }
2033  rss << " }";
2034  return rss.str();
2035  }
2036 
2037  template<typename R>
2039  static std::string convert( R const& range ) {
2040  return rangeToString( range );
2041  }
2042  };
2043 
2044  template <typename T, int SZ>
2045  struct StringMaker<T[SZ]> {
2046  static std::string convert(T const(&arr)[SZ]) {
2047  return rangeToString(arr);
2048  }
2049  };
2050 
2051 } // namespace Catch
2052 
2053 // Separate std::chrono::duration specialization
2054 #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2055 #include <ctime>
2056 #include <ratio>
2057 #include <chrono>
2058 
2059 namespace Catch {
2060 
2061 template <class Ratio>
2062 struct ratio_string {
2063  static std::string symbol();
2064 };
2065 
2066 template <class Ratio>
2067 std::string ratio_string<Ratio>::symbol() {
2069  rss << '[' << Ratio::num << '/'
2070  << Ratio::den << ']';
2071  return rss.str();
2072 }
2073 template <>
2074 struct ratio_string<std::atto> {
2075  static std::string symbol();
2076 };
2077 template <>
2078 struct ratio_string<std::femto> {
2079  static std::string symbol();
2080 };
2081 template <>
2082 struct ratio_string<std::pico> {
2083  static std::string symbol();
2084 };
2085 template <>
2086 struct ratio_string<std::nano> {
2087  static std::string symbol();
2088 };
2089 template <>
2090 struct ratio_string<std::micro> {
2091  static std::string symbol();
2092 };
2093 template <>
2094 struct ratio_string<std::milli> {
2095  static std::string symbol();
2096 };
2097 
2099  // std::chrono::duration specializations
2100  template<typename Value, typename Ratio>
2101  struct StringMaker<std::chrono::duration<Value, Ratio>> {
2102  static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2104  rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2105  return rss.str();
2106  }
2107  };
2108  template<typename Value>
2109  struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2110  static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2112  rss << duration.count() << " s";
2113  return rss.str();
2114  }
2115  };
2116  template<typename Value>
2117  struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2118  static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2120  rss << duration.count() << " m";
2121  return rss.str();
2122  }
2123  };
2124  template<typename Value>
2125  struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2126  static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2128  rss << duration.count() << " h";
2129  return rss.str();
2130  }
2131  };
2132 
2134  // std::chrono::time_point specialization
2135  // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2136  template<typename Clock, typename Duration>
2137  struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2138  static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2139  return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2140  }
2141  };
2142  // std::chrono::time_point<system_clock> specialization
2143  template<typename Duration>
2144  struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2145  static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2146  auto converted = std::chrono::system_clock::to_time_t(time_point);
2147 
2148 #ifdef _MSC_VER
2149  std::tm timeInfo = {};
2150  gmtime_s(&timeInfo, &converted);
2151 #else
2152  std::tm* timeInfo = std::gmtime(&converted);
2153 #endif
2154 
2155  auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2156  char timeStamp[timeStampSize];
2157  const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2158 
2159 #ifdef _MSC_VER
2160  std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2161 #else
2162  std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2163 #endif
2164  return std::string(timeStamp);
2165  }
2166  };
2167 }
2168 #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2169 
2170 #define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2171 namespace Catch { \
2172  template<> struct StringMaker<enumName> { \
2173  static std::string convert( enumName value ) { \
2174  static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2175  return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2176  } \
2177  }; \
2178 }
2179 
2180 #define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2181 
2182 #ifdef _MSC_VER
2183 #pragma warning(pop)
2184 #endif
2185 
2186 // end catch_tostring.h
2187 #include <iosfwd>
2188 
2189 #ifdef _MSC_VER
2190 #pragma warning(push)
2191 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2192 #pragma warning(disable:4018) // more "signed/unsigned mismatch"
2193 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2194 #pragma warning(disable:4180) // qualifier applied to function type has no meaning
2195 #pragma warning(disable:4800) // Forcing result to true or false
2196 #endif
2197 
2198 namespace Catch {
2199 
2201  auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2202  auto getResult() const -> bool { return m_result; }
2203  virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2204 
2205  ITransientExpression( bool isBinaryExpression, bool result )
2206  : m_isBinaryExpression( isBinaryExpression ),
2207  m_result( result )
2208  {}
2209 
2210  // We don't actually need a virtual destructor, but many static analysers
2211  // complain if it's not here :-(
2212  virtual ~ITransientExpression();
2213 
2214  bool m_isBinaryExpression;
2215  bool m_result;
2216 
2217  };
2218 
2219  void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2220 
2221  template<typename LhsT, typename RhsT>
2223  LhsT m_lhs;
2224  StringRef m_op;
2225  RhsT m_rhs;
2226 
2227  void streamReconstructedExpression( std::ostream &os ) const override {
2228  formatReconstructedExpression
2229  ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2230  }
2231 
2232  public:
2233  BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2234  : ITransientExpression{ true, comparisonResult },
2235  m_lhs( lhs ),
2236  m_op( op ),
2237  m_rhs( rhs )
2238  {}
2239 
2240  template<typename T>
2241  auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2242  static_assert(always_false<T>::value,
2243  "chained comparisons are not supported inside assertions, "
2244  "wrap the expression inside parentheses, or decompose it");
2245  }
2246 
2247  template<typename T>
2248  auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2249  static_assert(always_false<T>::value,
2250  "chained comparisons are not supported inside assertions, "
2251  "wrap the expression inside parentheses, or decompose it");
2252  }
2253 
2254  template<typename T>
2255  auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2256  static_assert(always_false<T>::value,
2257  "chained comparisons are not supported inside assertions, "
2258  "wrap the expression inside parentheses, or decompose it");
2259  }
2260 
2261  template<typename T>
2262  auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2263  static_assert(always_false<T>::value,
2264  "chained comparisons are not supported inside assertions, "
2265  "wrap the expression inside parentheses, or decompose it");
2266  }
2267 
2268  template<typename T>
2269  auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2270  static_assert(always_false<T>::value,
2271  "chained comparisons are not supported inside assertions, "
2272  "wrap the expression inside parentheses, or decompose it");
2273  }
2274 
2275  template<typename T>
2276  auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2277  static_assert(always_false<T>::value,
2278  "chained comparisons are not supported inside assertions, "
2279  "wrap the expression inside parentheses, or decompose it");
2280  }
2281 
2282  template<typename T>
2283  auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2284  static_assert(always_false<T>::value,
2285  "chained comparisons are not supported inside assertions, "
2286  "wrap the expression inside parentheses, or decompose it");
2287  }
2288 
2289  template<typename T>
2290  auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2291  static_assert(always_false<T>::value,
2292  "chained comparisons are not supported inside assertions, "
2293  "wrap the expression inside parentheses, or decompose it");
2294  }
2295  };
2296 
2297  template<typename LhsT>
2299  LhsT m_lhs;
2300 
2301  void streamReconstructedExpression( std::ostream &os ) const override {
2302  os << Catch::Detail::stringify( m_lhs );
2303  }
2304 
2305  public:
2306  explicit UnaryExpr( LhsT lhs )
2307  : ITransientExpression{ false, static_cast<bool>(lhs) },
2308  m_lhs( lhs )
2309  {}
2310  };
2311 
2312  // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2313  template<typename LhsT, typename RhsT>
2314  auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2315  template<typename T>
2316  auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2317  template<typename T>
2318  auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2319  template<typename T>
2320  auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2321  template<typename T>
2322  auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2323 
2324  template<typename LhsT, typename RhsT>
2325  auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2326  template<typename T>
2327  auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2328  template<typename T>
2329  auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2330  template<typename T>
2331  auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2332  template<typename T>
2333  auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2334 
2335  template<typename LhsT>
2336  class ExprLhs {
2337  LhsT m_lhs;
2338  public:
2339  explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2340 
2341  template<typename RhsT>
2342  auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2343  return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2344  }
2345  auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2346  return { m_lhs == rhs, m_lhs, "==", rhs };
2347  }
2348 
2349  template<typename RhsT>
2350  auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2351  return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2352  }
2353  auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2354  return { m_lhs != rhs, m_lhs, "!=", rhs };
2355  }
2356 
2357  template<typename RhsT>
2358  auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2359  return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2360  }
2361  template<typename RhsT>
2362  auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2363  return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2364  }
2365  template<typename RhsT>
2366  auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2367  return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2368  }
2369  template<typename RhsT>
2370  auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2371  return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2372  }
2373  template <typename RhsT>
2374  auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2375  return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
2376  }
2377  template <typename RhsT>
2378  auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2379  return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
2380  }
2381  template <typename RhsT>
2382  auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2383  return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
2384  }
2385 
2386  template<typename RhsT>
2387  auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2388  static_assert(always_false<RhsT>::value,
2389  "operator&& is not supported inside assertions, "
2390  "wrap the expression inside parentheses, or decompose it");
2391  }
2392 
2393  template<typename RhsT>
2394  auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2395  static_assert(always_false<RhsT>::value,
2396  "operator|| is not supported inside assertions, "
2397  "wrap the expression inside parentheses, or decompose it");
2398  }
2399 
2400  auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2401  return UnaryExpr<LhsT>{ m_lhs };
2402  }
2403  };
2404 
2405  void handleExpression( ITransientExpression const& expr );
2406 
2407  template<typename T>
2408  void handleExpression( ExprLhs<T> const& expr ) {
2409  handleExpression( expr.makeUnaryExpr() );
2410  }
2411 
2412  struct Decomposer {
2413  template<typename T>
2414  auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2415  return ExprLhs<T const&>{ lhs };
2416  }
2417 
2418  auto operator <=( bool value ) -> ExprLhs<bool> {
2419  return ExprLhs<bool>{ value };
2420  }
2421  };
2422 
2423 } // end namespace Catch
2424 
2425 #ifdef _MSC_VER
2426 #pragma warning(pop)
2427 #endif
2428 
2429 // end catch_decomposer.h
2430 // start catch_interfaces_capture.h
2431 
2432 #include <string>
2433 #include <chrono>
2434 
2435 namespace Catch {
2436 
2437  class AssertionResult;
2438  struct AssertionInfo;
2439  struct SectionInfo;
2440  struct SectionEndInfo;
2441  struct MessageInfo;
2442  struct MessageBuilder;
2443  struct Counts;
2444  struct AssertionReaction;
2445  struct SourceLineInfo;
2446 
2447  struct ITransientExpression;
2448  struct IGeneratorTracker;
2449 
2450 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2451  struct BenchmarkInfo;
2452  template <typename Duration = std::chrono::duration<double, std::nano>>
2453  struct BenchmarkStats;
2454 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2455 
2457 
2458  virtual ~IResultCapture();
2459 
2460  virtual bool sectionStarted( SectionInfo const& sectionInfo,
2461  Counts& assertions ) = 0;
2462  virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2463  virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2464 
2465  virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2466 
2467 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2468  virtual void benchmarkPreparing( std::string const& name ) = 0;
2469  virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2470  virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2471  virtual void benchmarkFailed( std::string const& error ) = 0;
2472 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2473 
2474  virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2475  virtual void popScopedMessage( MessageInfo const& message ) = 0;
2476 
2477  virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2478 
2479  virtual void handleFatalErrorCondition( StringRef message ) = 0;
2480 
2481  virtual void handleExpr
2482  ( AssertionInfo const& info,
2483  ITransientExpression const& expr,
2484  AssertionReaction& reaction ) = 0;
2485  virtual void handleMessage
2486  ( AssertionInfo const& info,
2487  ResultWas::OfType resultType,
2488  StringRef const& message,
2489  AssertionReaction& reaction ) = 0;
2490  virtual void handleUnexpectedExceptionNotThrown
2491  ( AssertionInfo const& info,
2492  AssertionReaction& reaction ) = 0;
2493  virtual void handleUnexpectedInflightException
2494  ( AssertionInfo const& info,
2495  std::string const& message,
2496  AssertionReaction& reaction ) = 0;
2497  virtual void handleIncomplete
2498  ( AssertionInfo const& info ) = 0;
2499  virtual void handleNonExpr
2500  ( AssertionInfo const &info,
2501  ResultWas::OfType resultType,
2502  AssertionReaction &reaction ) = 0;
2503 
2504  virtual bool lastAssertionPassed() = 0;
2505  virtual void assertionPassed() = 0;
2506 
2507  // Deprecated, do not use:
2508  virtual std::string getCurrentTestName() const = 0;
2509  virtual const AssertionResult* getLastResult() const = 0;
2510  virtual void exceptionEarlyReported() = 0;
2511  };
2512 
2513  IResultCapture& getResultCapture();
2514 }
2515 
2516 // end catch_interfaces_capture.h
2517 namespace Catch {
2518 
2520  struct AssertionResultData;
2521  struct IResultCapture;
2522  class RunContext;
2523 
2525  friend class AssertionHandler;
2526  friend struct AssertionStats;
2527  friend class RunContext;
2528 
2529  ITransientExpression const* m_transientExpression = nullptr;
2530  bool m_isNegated;
2531  public:
2532  LazyExpression( bool isNegated );
2533  LazyExpression( LazyExpression const& other );
2534  LazyExpression& operator = ( LazyExpression const& ) = delete;
2535 
2536  explicit operator bool() const;
2537 
2538  friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2539  };
2540 
2542  bool shouldDebugBreak = false;
2543  bool shouldThrow = false;
2544  };
2545 
2547  AssertionInfo m_assertionInfo;
2548  AssertionReaction m_reaction;
2549  bool m_completed = false;
2550  IResultCapture& m_resultCapture;
2551 
2552  public:
2554  ( StringRef const& macroName,
2555  SourceLineInfo const& lineInfo,
2556  StringRef capturedExpression,
2557  ResultDisposition::Flags resultDisposition );
2558  ~AssertionHandler() {
2559  if ( !m_completed ) {
2560  m_resultCapture.handleIncomplete( m_assertionInfo );
2561  }
2562  }
2563 
2564  template<typename T>
2565  void handleExpr( ExprLhs<T> const& expr ) {
2566  handleExpr( expr.makeUnaryExpr() );
2567  }
2568  void handleExpr( ITransientExpression const& expr );
2569 
2570  void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2571 
2572  void handleExceptionThrownAsExpected();
2573  void handleUnexpectedExceptionNotThrown();
2574  void handleExceptionNotThrownAsExpected();
2575  void handleThrowingCallSkipped();
2576  void handleUnexpectedInflightException();
2577 
2578  void complete();
2579  void setCompleted();
2580 
2581  // query
2582  auto allowThrows() const -> bool;
2583  };
2584 
2585  void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2586 
2587 } // namespace Catch
2588 
2589 // end catch_assertionhandler.h
2590 // start catch_message.h
2591 
2592 #include <string>
2593 #include <vector>
2594 
2595 namespace Catch {
2596 
2597  struct MessageInfo {
2598  MessageInfo( StringRef const& _macroName,
2599  SourceLineInfo const& _lineInfo,
2600  ResultWas::OfType _type );
2601 
2602  StringRef macroName;
2603  std::string message;
2604  SourceLineInfo lineInfo;
2605  ResultWas::OfType type;
2606  unsigned int sequence;
2607 
2608  bool operator == ( MessageInfo const& other ) const;
2609  bool operator < ( MessageInfo const& other ) const;
2610  private:
2611  static unsigned int globalCount;
2612  };
2613 
2614  struct MessageStream {
2615 
2616  template<typename T>
2617  MessageStream& operator << ( T const& value ) {
2618  m_stream << value;
2619  return *this;
2620  }
2621 
2622  ReusableStringStream m_stream;
2623  };
2624 
2626  MessageBuilder( StringRef const& macroName,
2627  SourceLineInfo const& lineInfo,
2628  ResultWas::OfType type );
2629 
2630  template<typename T>
2631  MessageBuilder& operator << ( T const& value ) {
2632  m_stream << value;
2633  return *this;
2634  }
2635 
2636  MessageInfo m_info;
2637  };
2638 
2640  public:
2641  explicit ScopedMessage( MessageBuilder const& builder );
2642  ScopedMessage( ScopedMessage& duplicate ) = delete;
2643  ScopedMessage( ScopedMessage&& old );
2644  ~ScopedMessage();
2645 
2646  MessageInfo m_info;
2647  bool m_moved;
2648  };
2649 
2650  class Capturer {
2651  std::vector<MessageInfo> m_messages;
2652  IResultCapture& m_resultCapture = getResultCapture();
2653  size_t m_captured = 0;
2654  public:
2655  Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2656  ~Capturer();
2657 
2658  void captureValue( size_t index, std::string const& value );
2659 
2660  template<typename T>
2661  void captureValues( size_t index, T const& value ) {
2662  captureValue( index, Catch::Detail::stringify( value ) );
2663  }
2664 
2665  template<typename T, typename... Ts>
2666  void captureValues( size_t index, T const& value, Ts const&... values ) {
2667  captureValue( index, Catch::Detail::stringify(value) );
2668  captureValues( index+1, values... );
2669  }
2670  };
2671 
2672 } // end namespace Catch
2673 
2674 // end catch_message.h
2675 #if !defined(CATCH_CONFIG_DISABLE)
2676 
2677 #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2678  #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2679 #else
2680  #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2681 #endif
2682 
2683 #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2684 
2686 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2687 // macros.
2688 #define INTERNAL_CATCH_TRY
2689 #define INTERNAL_CATCH_CATCH( capturer )
2690 
2691 #else // CATCH_CONFIG_FAST_COMPILE
2692 
2693 #define INTERNAL_CATCH_TRY try
2694 #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2695 
2696 #endif
2697 
2698 #define INTERNAL_CATCH_REACT( handler ) handler.complete();
2699 
2701 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2702  do { \
2703  CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2704  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2705  INTERNAL_CATCH_TRY { \
2706  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2707  CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2708  catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2709  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2710  } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2711  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2712  } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2713 
2715 #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2716  INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2717  if( Catch::getResultCapture().lastAssertionPassed() )
2718 
2720 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2721  INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2722  if( !Catch::getResultCapture().lastAssertionPassed() )
2723 
2725 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2726  do { \
2727  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2728  try { \
2729  static_cast<void>(__VA_ARGS__); \
2730  catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2731  } \
2732  catch( ... ) { \
2733  catchAssertionHandler.handleUnexpectedInflightException(); \
2734  } \
2735  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2736  } while( false )
2737 
2739 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2740  do { \
2741  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2742  if( catchAssertionHandler.allowThrows() ) \
2743  try { \
2744  static_cast<void>(__VA_ARGS__); \
2745  catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2746  } \
2747  catch( ... ) { \
2748  catchAssertionHandler.handleExceptionThrownAsExpected(); \
2749  } \
2750  else \
2751  catchAssertionHandler.handleThrowingCallSkipped(); \
2752  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2753  } while( false )
2754 
2756 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2757  do { \
2758  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2759  if( catchAssertionHandler.allowThrows() ) \
2760  try { \
2761  static_cast<void>(expr); \
2762  catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2763  } \
2764  catch( exceptionType const& ) { \
2765  catchAssertionHandler.handleExceptionThrownAsExpected(); \
2766  } \
2767  catch( ... ) { \
2768  catchAssertionHandler.handleUnexpectedInflightException(); \
2769  } \
2770  else \
2771  catchAssertionHandler.handleThrowingCallSkipped(); \
2772  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2773  } while( false )
2774 
2776 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2777  do { \
2778  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2779  catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2780  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2781  } while( false )
2782 
2784 #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2785  auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2786  varName.captureValues( 0, __VA_ARGS__ )
2787 
2789 #define INTERNAL_CATCH_INFO( macroName, log ) \
2790  Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2791 
2793 #define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2794  Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2795 
2797 // Although this is matcher-based, it can be used with just a string
2798 #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2799  do { \
2800  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2801  if( catchAssertionHandler.allowThrows() ) \
2802  try { \
2803  static_cast<void>(__VA_ARGS__); \
2804  catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2805  } \
2806  catch( ... ) { \
2807  Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2808  } \
2809  else \
2810  catchAssertionHandler.handleThrowingCallSkipped(); \
2811  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2812  } while( false )
2813 
2814 #endif // CATCH_CONFIG_DISABLE
2815 
2816 // end catch_capture.hpp
2817 // start catch_section.h
2818 
2819 // start catch_section_info.h
2820 
2821 // start catch_totals.h
2822 
2823 #include <cstddef>
2824 
2825 namespace Catch {
2826 
2827  struct Counts {
2828  Counts operator - ( Counts const& other ) const;
2829  Counts& operator += ( Counts const& other );
2830 
2831  std::size_t total() const;
2832  bool allPassed() const;
2833  bool allOk() const;
2834 
2835  std::size_t passed = 0;
2836  std::size_t failed = 0;
2837  std::size_t failedButOk = 0;
2838  };
2839 
2840  struct Totals {
2841 
2842  Totals operator - ( Totals const& other ) const;
2843  Totals& operator += ( Totals const& other );
2844 
2845  Totals delta( Totals const& prevTotals ) const;
2846 
2847  int error = 0;
2848  Counts assertions;
2849  Counts testCases;
2850  };
2851 }
2852 
2853 // end catch_totals.h
2854 #include <string>
2855 
2856 namespace Catch {
2857 
2858  struct SectionInfo {
2859  SectionInfo
2860  ( SourceLineInfo const& _lineInfo,
2861  std::string const& _name );
2862 
2863  // Deprecated
2864  SectionInfo
2865  ( SourceLineInfo const& _lineInfo,
2866  std::string const& _name,
2867  std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2868 
2869  std::string name;
2870  std::string description; // !Deprecated: this will always be empty
2871  SourceLineInfo lineInfo;
2872  };
2873 
2875  SectionInfo sectionInfo;
2876  Counts prevAssertions;
2877  double durationInSeconds;
2878  };
2879 
2880 } // end namespace Catch
2881 
2882 // end catch_section_info.h
2883 // start catch_timer.h
2884 
2885 #include <cstdint>
2886 
2887 namespace Catch {
2888 
2889  auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2890  auto getEstimatedClockResolution() -> uint64_t;
2891 
2892  class Timer {
2893  uint64_t m_nanoseconds = 0;
2894  public:
2895  void start();
2896  auto getElapsedNanoseconds() const -> uint64_t;
2897  auto getElapsedMicroseconds() const -> uint64_t;
2898  auto getElapsedMilliseconds() const -> unsigned int;
2899  auto getElapsedSeconds() const -> double;
2900  };
2901 
2902 } // namespace Catch
2903 
2904 // end catch_timer.h
2905 #include <string>
2906 
2907 namespace Catch {
2908 
2910  public:
2911  Section( SectionInfo const& info );
2912  ~Section();
2913 
2914  // This indicates whether the section should be executed or not
2915  explicit operator bool() const;
2916 
2917  private:
2918  SectionInfo m_info;
2919 
2920  std::string m_name;
2921  Counts m_assertions;
2922  bool m_sectionIncluded;
2923  Timer m_timer;
2924  };
2925 
2926 } // end namespace Catch
2927 
2928 #define INTERNAL_CATCH_SECTION( ... ) \
2929  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2930  CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2931  if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2932  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2933 
2934 #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2935  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2936  CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2937  if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2938  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2939 
2940 // end catch_section.h
2941 // start catch_interfaces_exception.h
2942 
2943 // start catch_interfaces_registry_hub.h
2944 
2945 #include <string>
2946 #include <memory>
2947 
2948 namespace Catch {
2949 
2950  class TestCase;
2951  struct ITestCaseRegistry;
2953  struct IExceptionTranslator;
2954  struct IReporterRegistry;
2955  struct IReporterFactory;
2956  struct ITagAliasRegistry;
2958 
2959  class StartupExceptionRegistry;
2960 
2961  using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2962 
2963  struct IRegistryHub {
2964  virtual ~IRegistryHub();
2965 
2966  virtual IReporterRegistry const& getReporterRegistry() const = 0;
2967  virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2968  virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2969  virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2970 
2971  virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2972  };
2973 
2975  virtual ~IMutableRegistryHub();
2976  virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2977  virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2978  virtual void registerTest( TestCase const& testInfo ) = 0;
2979  virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2980  virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2981  virtual void registerStartupException() noexcept = 0;
2982  virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2983  };
2984 
2985  IRegistryHub const& getRegistryHub();
2986  IMutableRegistryHub& getMutableRegistryHub();
2987  void cleanUp();
2988  std::string translateActiveException();
2989 
2990 }
2991 
2992 // end catch_interfaces_registry_hub.h
2993 #if defined(CATCH_CONFIG_DISABLE)
2994  #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2995  static std::string translatorName( signature )
2996 #endif
2997 
2998 #include <exception>
2999 #include <string>
3000 #include <vector>
3001 
3002 namespace Catch {
3003  using exceptionTranslateFunction = std::string(*)();
3004 
3005  struct IExceptionTranslator;
3006  using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3007 
3009  virtual ~IExceptionTranslator();
3010  virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
3011  };
3012 
3014  virtual ~IExceptionTranslatorRegistry();
3015 
3016  virtual std::string translateActiveException() const = 0;
3017  };
3018 
3020  template<typename T>
3021  class ExceptionTranslator : public IExceptionTranslator {
3022  public:
3023 
3024  ExceptionTranslator( std::string(*translateFunction)( T& ) )
3025  : m_translateFunction( translateFunction )
3026  {}
3027 
3028  std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
3029 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3030  return "";
3031 #else
3032  try {
3033  if( it == itEnd )
3034  std::rethrow_exception(std::current_exception());
3035  else
3036  return (*it)->translate( it+1, itEnd );
3037  }
3038  catch( T& ex ) {
3039  return m_translateFunction( ex );
3040  }
3041 #endif
3042  }
3043 
3044  protected:
3045  std::string(*m_translateFunction)( T& );
3046  };
3047 
3048  public:
3049  template<typename T>
3050  ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3051  getMutableRegistryHub().registerTranslator
3052  ( new ExceptionTranslator<T>( translateFunction ) );
3053  }
3054  };
3055 }
3056 
3058 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3059  static std::string translatorName( signature ); \
3060  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3061  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3062  namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3063  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3064  static std::string translatorName( signature )
3065 
3066 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3067 
3068 // end catch_interfaces_exception.h
3069 // start catch_approx.h
3070 
3071 #include <type_traits>
3072 
3073 namespace Catch {
3074 namespace Detail {
3075 
3076  class Approx {
3077  private:
3078  bool equalityComparisonImpl(double other) const;
3079  // Validates the new margin (margin >= 0)
3080  // out-of-line to avoid including stdexcept in the header
3081  void setMargin(double margin);
3082  // Validates the new epsilon (0 < epsilon < 1)
3083  // out-of-line to avoid including stdexcept in the header
3084  void setEpsilon(double epsilon);
3085 
3086  public:
3087  explicit Approx ( double value );
3088 
3089  static Approx custom();
3090 
3091  Approx operator-() const;
3092 
3093  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3094  Approx operator()( T const& value ) {
3095  Approx approx( static_cast<double>(value) );
3096  approx.m_epsilon = m_epsilon;
3097  approx.m_margin = m_margin;
3098  approx.m_scale = m_scale;
3099  return approx;
3100  }
3101 
3102  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3103  explicit Approx( T const& value ): Approx(static_cast<double>(value))
3104  {}
3105 
3106  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3107  friend bool operator == ( const T& lhs, Approx const& rhs ) {
3108  auto lhs_v = static_cast<double>(lhs);
3109  return rhs.equalityComparisonImpl(lhs_v);
3110  }
3111 
3112  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3113  friend bool operator == ( Approx const& lhs, const T& rhs ) {
3114  return operator==( rhs, lhs );
3115  }
3116 
3117  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3118  friend bool operator != ( T const& lhs, Approx const& rhs ) {
3119  return !operator==( lhs, rhs );
3120  }
3121 
3122  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3123  friend bool operator != ( Approx const& lhs, T const& rhs ) {
3124  return !operator==( rhs, lhs );
3125  }
3126 
3127  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3128  friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3129  return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3130  }
3131 
3132  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3133  friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3134  return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3135  }
3136 
3137  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3138  friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3139  return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3140  }
3141 
3142  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3143  friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3144  return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3145  }
3146 
3147  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3148  Approx& epsilon( T const& newEpsilon ) {
3149  double epsilonAsDouble = static_cast<double>(newEpsilon);
3150  setEpsilon(epsilonAsDouble);
3151  return *this;
3152  }
3153 
3154  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3155  Approx& margin( T const& newMargin ) {
3156  double marginAsDouble = static_cast<double>(newMargin);
3157  setMargin(marginAsDouble);
3158  return *this;
3159  }
3160 
3161  template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3162  Approx& scale( T const& newScale ) {
3163  m_scale = static_cast<double>(newScale);
3164  return *this;
3165  }
3166 
3167  std::string toString() const;
3168 
3169  private:
3170  double m_epsilon;
3171  double m_margin;
3172  double m_scale;
3173  double m_value;
3174  };
3175 } // end namespace Detail
3176 
3177 namespace literals {
3178  Detail::Approx operator "" _a(long double val);
3179  Detail::Approx operator "" _a(unsigned long long val);
3180 } // end namespace literals
3181 
3182 template<>
3184  static std::string convert(Catch::Detail::Approx const& value);
3185 };
3186 
3187 } // end namespace Catch
3188 
3189 // end catch_approx.h
3190 // start catch_string_manip.h
3191 
3192 #include <string>
3193 #include <iosfwd>
3194 #include <vector>
3195 
3196 namespace Catch {
3197 
3198  bool startsWith( std::string const& s, std::string const& prefix );
3199  bool startsWith( std::string const& s, char prefix );
3200  bool endsWith( std::string const& s, std::string const& suffix );
3201  bool endsWith( std::string const& s, char suffix );
3202  bool contains( std::string const& s, std::string const& infix );
3203  void toLowerInPlace( std::string& s );
3204  std::string toLower( std::string const& s );
3206  std::string trim( std::string const& str );
3208  StringRef trim(StringRef ref);
3209 
3210  // !!! Be aware, returns refs into original string - make sure original string outlives them
3211  std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3212  bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3213 
3214  struct pluralise {
3215  pluralise( std::size_t count, std::string const& label );
3216 
3217  friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3218 
3219  std::size_t m_count;
3220  std::string m_label;
3221  };
3222 }
3223 
3224 // end catch_string_manip.h
3225 #ifndef CATCH_CONFIG_DISABLE_MATCHERS
3226 // start catch_capture_matchers.h
3227 
3228 // start catch_matchers.h
3229 
3230 #include <string>
3231 #include <vector>
3232 
3233 namespace Catch {
3234 namespace Matchers {
3235  namespace Impl {
3236 
3237  template<typename ArgT> struct MatchAllOf;
3238  template<typename ArgT> struct MatchAnyOf;
3239  template<typename ArgT> struct MatchNotOf;
3240 
3242  public:
3243  MatcherUntypedBase() = default;
3244  MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3245  MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3246  std::string toString() const;
3247 
3248  protected:
3249  virtual ~MatcherUntypedBase();
3250  virtual std::string describe() const = 0;
3251  mutable std::string m_cachedToString;
3252  };
3253 
3254 #ifdef __clang__
3255 # pragma clang diagnostic push
3256 # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3257 #endif
3258 
3259  template<typename ObjectT>
3260  struct MatcherMethod {
3261  virtual bool match( ObjectT const& arg ) const = 0;
3262  };
3263 
3264 #if defined(__OBJC__)
3265  // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3266  // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3267  template<>
3268  struct MatcherMethod<NSString*> {
3269  virtual bool match( NSString* arg ) const = 0;
3270  };
3271 #endif
3272 
3273 #ifdef __clang__
3274 # pragma clang diagnostic pop
3275 #endif
3276 
3277  template<typename T>
3279 
3280  MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3281  MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3282  MatchNotOf<T> operator ! () const;
3283  };
3284 
3285  template<typename ArgT>
3286  struct MatchAllOf : MatcherBase<ArgT> {
3287  bool match( ArgT const& arg ) const override {
3288  for( auto matcher : m_matchers ) {
3289  if (!matcher->match(arg))
3290  return false;
3291  }
3292  return true;
3293  }
3294  std::string describe() const override {
3295  std::string description;
3296  description.reserve( 4 + m_matchers.size()*32 );
3297  description += "( ";
3298  bool first = true;
3299  for( auto matcher : m_matchers ) {
3300  if( first )
3301  first = false;
3302  else
3303  description += " and ";
3304  description += matcher->toString();
3305  }
3306  description += " )";
3307  return description;
3308  }
3309 
3310  MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
3311  auto copy(*this);
3312  copy.m_matchers.push_back( &other );
3313  return copy;
3314  }
3315 
3316  std::vector<MatcherBase<ArgT> const*> m_matchers;
3317  };
3318  template<typename ArgT>
3319  struct MatchAnyOf : MatcherBase<ArgT> {
3320 
3321  bool match( ArgT const& arg ) const override {
3322  for( auto matcher : m_matchers ) {
3323  if (matcher->match(arg))
3324  return true;
3325  }
3326  return false;
3327  }
3328  std::string describe() const override {
3329  std::string description;
3330  description.reserve( 4 + m_matchers.size()*32 );
3331  description += "( ";
3332  bool first = true;
3333  for( auto matcher : m_matchers ) {
3334  if( first )
3335  first = false;
3336  else
3337  description += " or ";
3338  description += matcher->toString();
3339  }
3340  description += " )";
3341  return description;
3342  }
3343 
3344  MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
3345  auto copy(*this);
3346  copy.m_matchers.push_back( &other );
3347  return copy;
3348  }
3349 
3350  std::vector<MatcherBase<ArgT> const*> m_matchers;
3351  };
3352 
3353  template<typename ArgT>
3354  struct MatchNotOf : MatcherBase<ArgT> {
3355 
3356  MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3357 
3358  bool match( ArgT const& arg ) const override {
3359  return !m_underlyingMatcher.match( arg );
3360  }
3361 
3362  std::string describe() const override {
3363  return "not " + m_underlyingMatcher.toString();
3364  }
3365  MatcherBase<ArgT> const& m_underlyingMatcher;
3366  };
3367 
3368  template<typename T>
3370  return MatchAllOf<T>() && *this && other;
3371  }
3372  template<typename T>
3374  return MatchAnyOf<T>() || *this || other;
3375  }
3376  template<typename T>
3378  return MatchNotOf<T>( *this );
3379  }
3380 
3381  } // namespace Impl
3382 
3383 } // namespace Matchers
3384 
3385 using namespace Matchers;
3387 
3388 } // namespace Catch
3389 
3390 // end catch_matchers.h
3391 // start catch_matchers_exception.hpp
3392 
3393 namespace Catch {
3394 namespace Matchers {
3395 namespace Exception {
3396 
3397 class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3398  std::string m_message;
3399 public:
3400 
3401  ExceptionMessageMatcher(std::string const& message):
3402  m_message(message)
3403  {}
3404 
3405  bool match(std::exception const& ex) const override;
3406 
3407  std::string describe() const override;
3408 };
3409 
3410 } // namespace Exception
3411 
3412 Exception::ExceptionMessageMatcher Message(std::string const& message);
3413 
3414 } // namespace Matchers
3415 } // namespace Catch
3416 
3417 // end catch_matchers_exception.hpp
3418 // start catch_matchers_floating.h
3419 
3420 namespace Catch {
3421 namespace Matchers {
3422 
3423  namespace Floating {
3424 
3425  enum class FloatingPointKind : uint8_t;
3426 
3427  struct WithinAbsMatcher : MatcherBase<double> {
3428  WithinAbsMatcher(double target, double margin);
3429  bool match(double const& matchee) const override;
3430  std::string describe() const override;
3431  private:
3432  double m_target;
3433  double m_margin;
3434  };
3435 
3436  struct WithinUlpsMatcher : MatcherBase<double> {
3437  WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3438  bool match(double const& matchee) const override;
3439  std::string describe() const override;
3440  private:
3441  double m_target;
3442  uint64_t m_ulps;
3443  FloatingPointKind m_type;
3444  };
3445 
3446  // Given IEEE-754 format for floats and doubles, we can assume
3447  // that float -> double promotion is lossless. Given this, we can
3448  // assume that if we do the standard relative comparison of
3449  // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3450  // the same result if we do this for floats, as if we do this for
3451  // doubles that were promoted from floats.
3452  struct WithinRelMatcher : MatcherBase<double> {
3453  WithinRelMatcher(double target, double epsilon);
3454  bool match(double const& matchee) const override;
3455  std::string describe() const override;
3456  private:
3457  double m_target;
3458  double m_epsilon;
3459  };
3460 
3461  } // namespace Floating
3462 
3463  // The following functions create the actual matcher objects.
3464  // This allows the types to be inferred
3465  Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3466  Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3467  Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3468  Floating::WithinRelMatcher WithinRel(double target, double eps);
3469  // defaults epsilon to 100*numeric_limits<double>::epsilon()
3470  Floating::WithinRelMatcher WithinRel(double target);
3471  Floating::WithinRelMatcher WithinRel(float target, float eps);
3472  // defaults epsilon to 100*numeric_limits<float>::epsilon()
3473  Floating::WithinRelMatcher WithinRel(float target);
3474 
3475 } // namespace Matchers
3476 } // namespace Catch
3477 
3478 // end catch_matchers_floating.h
3479 // start catch_matchers_generic.hpp
3480 
3481 #include <functional>
3482 #include <string>
3483 
3484 namespace Catch {
3485 namespace Matchers {
3486 namespace Generic {
3487 
3488 namespace Detail {
3489  std::string finalizeDescription(const std::string& desc);
3490 }
3491 
3492 template <typename T>
3493 class PredicateMatcher : public MatcherBase<T> {
3494  std::function<bool(T const&)> m_predicate;
3495  std::string m_description;
3496 public:
3497 
3498  PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3499  :m_predicate(std::move(elem)),
3500  m_description(Detail::finalizeDescription(descr))
3501  {}
3502 
3503  bool match( T const& item ) const override {
3504  return m_predicate(item);
3505  }
3506 
3507  std::string describe() const override {
3508  return m_description;
3509  }
3510 };
3511 
3512 } // namespace Generic
3513 
3514  // The following functions create the actual matcher objects.
3515  // The user has to explicitly specify type to the function, because
3516  // inferring std::function<bool(T const&)> is hard (but possible) and
3517  // requires a lot of TMP.
3518  template<typename T>
3519  Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3520  return Generic::PredicateMatcher<T>(predicate, description);
3521  }
3522 
3523 } // namespace Matchers
3524 } // namespace Catch
3525 
3526 // end catch_matchers_generic.hpp
3527 // start catch_matchers_string.h
3528 
3529 #include <string>
3530 
3531 namespace Catch {
3532 namespace Matchers {
3533 
3534  namespace StdString {
3535 
3537  {
3538  CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3539  std::string adjustString( std::string const& str ) const;
3540  std::string caseSensitivitySuffix() const;
3541 
3542  CaseSensitive::Choice m_caseSensitivity;
3543  std::string m_str;
3544  };
3545 
3546  struct StringMatcherBase : MatcherBase<std::string> {
3547  StringMatcherBase( std::string const& operation, CasedString const& comparator );
3548  std::string describe() const override;
3549 
3550  CasedString m_comparator;
3551  std::string m_operation;
3552  };
3553 
3555  EqualsMatcher( CasedString const& comparator );
3556  bool match( std::string const& source ) const override;
3557  };
3559  ContainsMatcher( CasedString const& comparator );
3560  bool match( std::string const& source ) const override;
3561  };
3563  StartsWithMatcher( CasedString const& comparator );
3564  bool match( std::string const& source ) const override;
3565  };
3567  EndsWithMatcher( CasedString const& comparator );
3568  bool match( std::string const& source ) const override;
3569  };
3570 
3571  struct RegexMatcher : MatcherBase<std::string> {
3572  RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3573  bool match( std::string const& matchee ) const override;
3574  std::string describe() const override;
3575 
3576  private:
3577  std::string m_regex;
3578  CaseSensitive::Choice m_caseSensitivity;
3579  };
3580 
3581  } // namespace StdString
3582 
3583  // The following functions create the actual matcher objects.
3584  // This allows the types to be inferred
3585 
3586  StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3587  StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3588  StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3589  StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3590  StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3591 
3592 } // namespace Matchers
3593 } // namespace Catch
3594 
3595 // end catch_matchers_string.h
3596 // start catch_matchers_vector.h
3597 
3598 #include <algorithm>
3599 
3600 namespace Catch {
3601 namespace Matchers {
3602 
3603  namespace Vector {
3604  template<typename T, typename Alloc>
3605  struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3606 
3607  ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3608 
3609  bool match(std::vector<T, Alloc> const &v) const override {
3610  for (auto const& el : v) {
3611  if (el == m_comparator) {
3612  return true;
3613  }
3614  }
3615  return false;
3616  }
3617 
3618  std::string describe() const override {
3619  return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3620  }
3621 
3622  T const& m_comparator;
3623  };
3624 
3625  template<typename T, typename AllocComp, typename AllocMatch>
3626  struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3627 
3628  ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3629 
3630  bool match(std::vector<T, AllocMatch> const &v) const override {
3631  // !TBD: see note in EqualsMatcher
3632  if (m_comparator.size() > v.size())
3633  return false;
3634  for (auto const& comparator : m_comparator) {
3635  auto present = false;
3636  for (const auto& el : v) {
3637  if (el == comparator) {
3638  present = true;
3639  break;
3640  }
3641  }
3642  if (!present) {
3643  return false;
3644  }
3645  }
3646  return true;
3647  }
3648  std::string describe() const override {
3649  return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3650  }
3651 
3652  std::vector<T, AllocComp> const& m_comparator;
3653  };
3654 
3655  template<typename T, typename AllocComp, typename AllocMatch>
3656  struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3657 
3658  EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3659 
3660  bool match(std::vector<T, AllocMatch> const &v) const override {
3661  // !TBD: This currently works if all elements can be compared using !=
3662  // - a more general approach would be via a compare template that defaults
3663  // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3664  // - then just call that directly
3665  if (m_comparator.size() != v.size())
3666  return false;
3667  for (std::size_t i = 0; i < v.size(); ++i)
3668  if (m_comparator[i] != v[i])
3669  return false;
3670  return true;
3671  }
3672  std::string describe() const override {
3673  return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3674  }
3675  std::vector<T, AllocComp> const& m_comparator;
3676  };
3677 
3678  template<typename T, typename AllocComp, typename AllocMatch>
3679  struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3680 
3681  ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
3682 
3683  bool match(std::vector<T, AllocMatch> const &v) const override {
3684  if (m_comparator.size() != v.size())
3685  return false;
3686  for (std::size_t i = 0; i < v.size(); ++i)
3687  if (m_comparator[i] != approx(v[i]))
3688  return false;
3689  return true;
3690  }
3691  std::string describe() const override {
3692  return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3693  }
3694  template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3695  ApproxMatcher& epsilon( T const& newEpsilon ) {
3696  approx.epsilon(newEpsilon);
3697  return *this;
3698  }
3699  template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3700  ApproxMatcher& margin( T const& newMargin ) {
3701  approx.margin(newMargin);
3702  return *this;
3703  }
3704  template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3705  ApproxMatcher& scale( T const& newScale ) {
3706  approx.scale(newScale);
3707  return *this;
3708  }
3709 
3710  std::vector<T, AllocComp> const& m_comparator;
3711  mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3712  };
3713 
3714  template<typename T, typename AllocComp, typename AllocMatch>
3715  struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3716  UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
3717  bool match(std::vector<T, AllocMatch> const& vec) const override {
3718  if (m_target.size() != vec.size()) {
3719  return false;
3720  }
3721  return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3722  }
3723 
3724  std::string describe() const override {
3725  return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3726  }
3727  private:
3728  std::vector<T, AllocComp> const& m_target;
3729  };
3730 
3731  } // namespace Vector
3732 
3733  // The following functions create the actual matcher objects.
3734  // This allows the types to be inferred
3735 
3736  template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3737  Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
3739  }
3740 
3741  template<typename T, typename Alloc = std::allocator<T>>
3742  Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
3743  return Vector::ContainsElementMatcher<T, Alloc>( comparator );
3744  }
3745 
3746  template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3747  Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
3749  }
3750 
3751  template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3752  Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
3754  }
3755 
3756  template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3757  Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
3759  }
3760 
3761 } // namespace Matchers
3762 } // namespace Catch
3763 
3764 // end catch_matchers_vector.h
3765 namespace Catch {
3766 
3767  template<typename ArgT, typename MatcherT>
3769  ArgT const& m_arg;
3770  MatcherT m_matcher;
3771  StringRef m_matcherString;
3772  public:
3773  MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3774  : ITransientExpression{ true, matcher.match( arg ) },
3775  m_arg( arg ),
3776  m_matcher( matcher ),
3777  m_matcherString( matcherString )
3778  {}
3779 
3780  void streamReconstructedExpression( std::ostream &os ) const override {
3781  auto matcherAsString = m_matcher.toString();
3782  os << Catch::Detail::stringify( m_arg ) << ' ';
3783  if( matcherAsString == Detail::unprintableString )
3784  os << m_matcherString;
3785  else
3786  os << matcherAsString;
3787  }
3788  };
3789 
3791 
3792  void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3793 
3794  template<typename ArgT, typename MatcherT>
3795  auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3796  return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3797  }
3798 
3799 } // namespace Catch
3800 
3802 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3803  do { \
3804  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3805  INTERNAL_CATCH_TRY { \
3806  catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3807  } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3808  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3809  } while( false )
3810 
3812 #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3813  do { \
3814  Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3815  if( catchAssertionHandler.allowThrows() ) \
3816  try { \
3817  static_cast<void>(__VA_ARGS__ ); \
3818  catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3819  } \
3820  catch( exceptionType const& ex ) { \
3821  catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3822  } \
3823  catch( ... ) { \
3824  catchAssertionHandler.handleUnexpectedInflightException(); \
3825  } \
3826  else \
3827  catchAssertionHandler.handleThrowingCallSkipped(); \
3828  INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3829  } while( false )
3830 
3831 // end catch_capture_matchers.h
3832 #endif
3833 // start catch_generators.hpp
3834 
3835 // start catch_interfaces_generatortracker.h
3836 
3837 
3838 #include <memory>
3839 
3840 namespace Catch {
3841 
3842  namespace Generators {
3844  public:
3845  GeneratorUntypedBase() = default;
3846  virtual ~GeneratorUntypedBase();
3847  // Attempts to move the generator to the next element
3848  //
3849  // Returns true iff the move succeeded (and a valid element
3850  // can be retrieved).
3851  virtual bool next() = 0;
3852  };
3853  using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3854 
3855  } // namespace Generators
3856 
3858  virtual ~IGeneratorTracker();
3859  virtual auto hasGenerator() const -> bool = 0;
3860  virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3861  virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3862  };
3863 
3864 } // namespace Catch
3865 
3866 // end catch_interfaces_generatortracker.h
3867 // start catch_enforce.h
3868 
3869 #include <exception>
3870 
3871 namespace Catch {
3872 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3873  template <typename Ex>
3874  [[noreturn]]
3875  void throw_exception(Ex const& e) {
3876  throw e;
3877  }
3878 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
3879  [[noreturn]]
3880  void throw_exception(std::exception const& e);
3881 #endif
3882 
3883  [[noreturn]]
3884  void throw_logic_error(std::string const& msg);
3885  [[noreturn]]
3886  void throw_domain_error(std::string const& msg);
3887  [[noreturn]]
3888  void throw_runtime_error(std::string const& msg);
3889 
3890 } // namespace Catch;
3891 
3892 #define CATCH_MAKE_MSG(...) \
3893  (Catch::ReusableStringStream() << __VA_ARGS__).str()
3894 
3895 #define CATCH_INTERNAL_ERROR(...) \
3896  Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3897 
3898 #define CATCH_ERROR(...) \
3899  Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3900 
3901 #define CATCH_RUNTIME_ERROR(...) \
3902  Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3903 
3904 #define CATCH_ENFORCE( condition, ... ) \
3905  do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3906 
3907 // end catch_enforce.h
3908 #include <memory>
3909 #include <vector>
3910 #include <cassert>
3911 
3912 #include <utility>
3913 #include <exception>
3914 
3915 namespace Catch {
3916 
3917 class GeneratorException : public std::exception {
3918  const char* const m_msg = "";
3919 
3920 public:
3921  GeneratorException(const char* msg):
3922  m_msg(msg)
3923  {}
3924 
3925  const char* what() const noexcept override final;
3926 };
3927 
3928 namespace Generators {
3929 
3930  // !TBD move this into its own location?
3931  namespace pf{
3932  template<typename T, typename... Args>
3933  std::unique_ptr<T> make_unique( Args&&... args ) {
3934  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3935  }
3936  }
3937 
3938  template<typename T>
3940  virtual ~IGenerator() = default;
3941 
3942  // Returns the current element of the generator
3943  //
3944  // \Precondition The generator is either freshly constructed,
3945  // or the last call to `next()` returned true
3946  virtual T const& get() const = 0;
3947  using type = T;
3948  };
3949 
3950  template<typename T>
3951  class SingleValueGenerator final : public IGenerator<T> {
3952  T m_value;
3953  public:
3954  SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3955 
3956  T const& get() const override {
3957  return m_value;
3958  }
3959  bool next() override {
3960  return false;
3961  }
3962  };
3963 
3964  template<typename T>
3965  class FixedValuesGenerator final : public IGenerator<T> {
3966  static_assert(!std::is_same<T, bool>::value,
3967  "FixedValuesGenerator does not support bools because of std::vector<bool>"
3968  "specialization, use SingleValue Generator instead.");
3969  std::vector<T> m_values;
3970  size_t m_idx = 0;
3971  public:
3972  FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3973 
3974  T const& get() const override {
3975  return m_values[m_idx];
3976  }
3977  bool next() override {
3978  ++m_idx;
3979  return m_idx < m_values.size();
3980  }
3981  };
3982 
3983  template <typename T>
3984  class GeneratorWrapper final {
3985  std::unique_ptr<IGenerator<T>> m_generator;
3986  public:
3987  GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3988  m_generator(std::move(generator))
3989  {}
3990  T const& get() const {
3991  return m_generator->get();
3992  }
3993  bool next() {
3994  return m_generator->next();
3995  }
3996  };
3997 
3998  template <typename T>
3999  GeneratorWrapper<T> value(T&& value) {
4000  return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4001  }
4002  template <typename T>
4003  GeneratorWrapper<T> values(std::initializer_list<T> values) {
4004  return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4005  }
4006 
4007  template<typename T>
4008  class Generators : public IGenerator<T> {
4009  std::vector<GeneratorWrapper<T>> m_generators;
4010  size_t m_current = 0;
4011 
4012  void populate(GeneratorWrapper<T>&& generator) {
4013  m_generators.emplace_back(std::move(generator));
4014  }
4015  void populate(T&& val) {
4016  m_generators.emplace_back(value(std::forward<T>(val)));
4017  }
4018  template<typename U>
4019  void populate(U&& val) {
4020  populate(T(std::forward<U>(val)));
4021  }
4022  template<typename U, typename... Gs>
4023  void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4024  populate(std::forward<U>(valueOrGenerator));
4025  populate(std::forward<Gs>(moreGenerators)...);
4026  }
4027 
4028  public:
4029  template <typename... Gs>
4030  Generators(Gs &&... moreGenerators) {
4031  m_generators.reserve(sizeof...(Gs));
4032  populate(std::forward<Gs>(moreGenerators)...);
4033  }
4034 
4035  T const& get() const override {
4036  return m_generators[m_current].get();
4037  }
4038 
4039  bool next() override {
4040  if (m_current >= m_generators.size()) {
4041  return false;
4042  }
4043  const bool current_status = m_generators[m_current].next();
4044  if (!current_status) {
4045  ++m_current;
4046  }
4047  return m_current < m_generators.size();
4048  }
4049  };
4050 
4051  template<typename... Ts>
4052  GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
4053  return values<std::tuple<Ts...>>( tuples );
4054  }
4055 
4056  // Tag type to signal that a generator sequence should convert arguments to a specific type
4057  template <typename T>
4058  struct as {};
4059 
4060  template<typename T, typename... Gs>
4061  auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
4062  return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4063  }
4064  template<typename T>
4065  auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4066  return Generators<T>(std::move(generator));
4067  }
4068  template<typename T, typename... Gs>
4069  auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4070  return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4071  }
4072  template<typename T, typename U, typename... Gs>
4073  auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4074  return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4075  }
4076 
4077  auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
4078 
4079  template<typename L>
4080  // Note: The type after -> is weird, because VS2015 cannot parse
4081  // the expression used in the typedef inside, when it is in
4082  // return type. Yeah.
4083  auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4084  using UnderlyingType = typename decltype(generatorExpression())::type;
4085 
4086  IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4087  if (!tracker.hasGenerator()) {
4088  tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4089  }
4090 
4091  auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
4092  return generator.get();
4093  }
4094 
4095 } // namespace Generators
4096 } // namespace Catch
4097 
4098 #define GENERATE( ... ) \
4099  Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4100  CATCH_INTERNAL_LINEINFO, \
4101  [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4102 #define GENERATE_COPY( ... ) \
4103  Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4104  CATCH_INTERNAL_LINEINFO, \
4105  [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4106 #define GENERATE_REF( ... ) \
4107  Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4108  CATCH_INTERNAL_LINEINFO, \
4109  [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4110 
4111 // end catch_generators.hpp
4112 // start catch_generators_generic.hpp
4113 
4114 namespace Catch {
4115 namespace Generators {
4116 
4117  template <typename T>
4118  class TakeGenerator : public IGenerator<T> {
4119  GeneratorWrapper<T> m_generator;
4120  size_t m_returned = 0;
4121  size_t m_target;
4122  public:
4123  TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4124  m_generator(std::move(generator)),
4125  m_target(target)
4126  {
4127  assert(target != 0 && "Empty generators are not allowed");
4128  }
4129  T const& get() const override {
4130  return m_generator.get();
4131  }
4132  bool next() override {
4133  ++m_returned;
4134  if (m_returned >= m_target) {
4135  return false;
4136  }
4137 
4138  const auto success = m_generator.next();
4139  // If the underlying generator does not contain enough values
4140  // then we cut short as well
4141  if (!success) {
4142  m_returned = m_target;
4143  }
4144  return success;
4145  }
4146  };
4147 
4148  template <typename T>
4149  GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4150  return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4151  }
4152 
4153  template <typename T, typename Predicate>
4154  class FilterGenerator : public IGenerator<T> {
4155  GeneratorWrapper<T> m_generator;
4156  Predicate m_predicate;
4157  public:
4158  template <typename P = Predicate>
4159  FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4160  m_generator(std::move(generator)),
4161  m_predicate(std::forward<P>(pred))
4162  {
4163  if (!m_predicate(m_generator.get())) {
4164  // It might happen that there are no values that pass the
4165  // filter. In that case we throw an exception.
4166  auto has_initial_value = next();
4167  if (!has_initial_value) {
4168  Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4169  }
4170  }
4171  }
4172 
4173  T const& get() const override {
4174  return m_generator.get();
4175  }
4176 
4177  bool next() override {
4178  bool success = m_generator.next();
4179  if (!success) {
4180  return false;
4181  }
4182  while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4183  return success;
4184  }
4185  };
4186 
4187  template <typename T, typename Predicate>
4188  GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4189  return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4190  }
4191 
4192  template <typename T>
4193  class RepeatGenerator : public IGenerator<T> {
4194  static_assert(!std::is_same<T, bool>::value,
4195  "RepeatGenerator currently does not support bools"
4196  "because of std::vector<bool> specialization");
4197  GeneratorWrapper<T> m_generator;
4198  mutable std::vector<T> m_returned;
4199  size_t m_target_repeats;
4200  size_t m_current_repeat = 0;
4201  size_t m_repeat_index = 0;
4202  public:
4203  RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4204  m_generator(std::move(generator)),
4205  m_target_repeats(repeats)
4206  {
4207  assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4208  }
4209 
4210  T const& get() const override {
4211  if (m_current_repeat == 0) {
4212  m_returned.push_back(m_generator.get());
4213  return m_returned.back();
4214  }
4215  return m_returned[m_repeat_index];
4216  }
4217 
4218  bool next() override {
4219  // There are 2 basic cases:
4220  // 1) We are still reading the generator
4221  // 2) We are reading our own cache
4222 
4223  // In the first case, we need to poke the underlying generator.
4224  // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4225  if (m_current_repeat == 0) {
4226  const auto success = m_generator.next();
4227  if (!success) {
4228  ++m_current_repeat;
4229  }
4230  return m_current_repeat < m_target_repeats;
4231  }
4232 
4233  // In the second case, we need to move indices forward and check that we haven't run up against the end
4234  ++m_repeat_index;
4235  if (m_repeat_index == m_returned.size()) {
4236  m_repeat_index = 0;
4237  ++m_current_repeat;
4238  }
4239  return m_current_repeat < m_target_repeats;
4240  }
4241  };
4242 
4243  template <typename T>
4244  GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4245  return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4246  }
4247 
4248  template <typename T, typename U, typename Func>
4249  class MapGenerator : public IGenerator<T> {
4250  // TBD: provide static assert for mapping function, for friendly error message
4251  GeneratorWrapper<U> m_generator;
4252  Func m_function;
4253  // To avoid returning dangling reference, we have to save the values
4254  T m_cache;
4255  public:
4256  template <typename F2 = Func>
4257  MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4258  m_generator(std::move(generator)),
4259  m_function(std::forward<F2>(function)),
4260  m_cache(m_function(m_generator.get()))
4261  {}
4262 
4263  T const& get() const override {
4264  return m_cache;
4265  }
4266  bool next() override {
4267  const auto success = m_generator.next();
4268  if (success) {
4269  m_cache = m_function(m_generator.get());
4270  }
4271  return success;
4272  }
4273  };
4274 
4275  template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4276  GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4277  return GeneratorWrapper<T>(
4278  pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4279  );
4280  }
4281 
4282  template <typename T, typename U, typename Func>
4283  GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4284  return GeneratorWrapper<T>(
4285  pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4286  );
4287  }
4288 
4289  template <typename T>
4290  class ChunkGenerator final : public IGenerator<std::vector<T>> {
4291  std::vector<T> m_chunk;
4292  size_t m_chunk_size;
4293  GeneratorWrapper<T> m_generator;
4294  bool m_used_up = false;
4295  public:
4296  ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4297  m_chunk_size(size), m_generator(std::move(generator))
4298  {
4299  m_chunk.reserve(m_chunk_size);
4300  if (m_chunk_size != 0) {
4301  m_chunk.push_back(m_generator.get());
4302  for (size_t i = 1; i < m_chunk_size; ++i) {
4303  if (!m_generator.next()) {
4304  Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4305  }
4306  m_chunk.push_back(m_generator.get());
4307  }
4308  }
4309  }
4310  std::vector<T> const& get() const override {
4311  return m_chunk;
4312  }
4313  bool next() override {
4314  m_chunk.clear();
4315  for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4316  if (!m_generator.next()) {
4317  return false;
4318  }
4319  m_chunk.push_back(m_generator.get());
4320  }
4321  return true;
4322  }
4323  };
4324 
4325  template <typename T>
4326  GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4328  pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4329  );
4330  }
4331 
4332 } // namespace Generators
4333 } // namespace Catch
4334 
4335 // end catch_generators_generic.hpp
4336 // start catch_generators_specific.hpp
4337 
4338 // start catch_context.h
4339 
4340 #include <memory>
4341 
4342 namespace Catch {
4343 
4344  struct IResultCapture;
4345  struct IRunner;
4346  struct IConfig;
4347  struct IMutableContext;
4348 
4349  using IConfigPtr = std::shared_ptr<IConfig const>;
4350 
4351  struct IContext
4352  {
4353  virtual ~IContext();
4354 
4355  virtual IResultCapture* getResultCapture() = 0;
4356  virtual IRunner* getRunner() = 0;
4357  virtual IConfigPtr const& getConfig() const = 0;
4358  };
4359 
4361  {
4362  virtual ~IMutableContext();
4363  virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4364  virtual void setRunner( IRunner* runner ) = 0;
4365  virtual void setConfig( IConfigPtr const& config ) = 0;
4366 
4367  private:
4368  static IMutableContext *currentContext;
4369  friend IMutableContext& getCurrentMutableContext();
4370  friend void cleanUpContext();
4371  static void createContext();
4372  };
4373 
4374  inline IMutableContext& getCurrentMutableContext()
4375  {
4376  if( !IMutableContext::currentContext )
4377  IMutableContext::createContext();
4378  // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4379  return *IMutableContext::currentContext;
4380  }
4381 
4382  inline IContext& getCurrentContext()
4383  {
4384  return getCurrentMutableContext();
4385  }
4386 
4387  void cleanUpContext();
4388 
4389  class SimplePcg32;
4390  SimplePcg32& rng();
4391 }
4392 
4393 // end catch_context.h
4394 // start catch_interfaces_config.h
4395 
4396 // start catch_option.hpp
4397 
4398 namespace Catch {
4399 
4400  // An optional type
4401  template<typename T>
4402  class Option {
4403  public:
4404  Option() : nullableValue( nullptr ) {}
4405  Option( T const& _value )
4406  : nullableValue( new( storage ) T( _value ) )
4407  {}
4408  Option( Option const& _other )
4409  : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4410  {}
4411 
4412  ~Option() {
4413  reset();
4414  }
4415 
4416  Option& operator= ( Option const& _other ) {
4417  if( &_other != this ) {
4418  reset();
4419  if( _other )
4420  nullableValue = new( storage ) T( *_other );
4421  }
4422  return *this;
4423  }
4424  Option& operator = ( T const& _value ) {
4425  reset();
4426  nullableValue = new( storage ) T( _value );
4427  return *this;
4428  }
4429 
4430  void reset() {
4431  if( nullableValue )
4432  nullableValue->~T();
4433  nullableValue = nullptr;
4434  }
4435 
4436  T& operator*() { return *nullableValue; }
4437  T const& operator*() const { return *nullableValue; }
4438  T* operator->() { return nullableValue; }
4439  const T* operator->() const { return nullableValue; }
4440 
4441  T valueOr( T const& defaultValue ) const {
4442  return nullableValue ? *nullableValue : defaultValue;
4443  }
4444 
4445  bool some() const { return nullableValue != nullptr; }
4446  bool none() const { return nullableValue == nullptr; }
4447 
4448  bool operator !() const { return nullableValue == nullptr; }
4449  explicit operator bool() const {
4450  return some();
4451  }
4452 
4453  private:
4454  T *nullableValue;
4455  alignas(alignof(T)) char storage[sizeof(T)];
4456  };
4457 
4458 } // end namespace Catch
4459 
4460 // end catch_option.hpp
4461 #include <chrono>
4462 #include <iosfwd>
4463 #include <string>
4464 #include <vector>
4465 #include <memory>
4466 
4467 namespace Catch {
4468 
4469  enum class Verbosity {
4470  Quiet = 0,
4471  Normal,
4472  High
4473  };
4474 
4475  struct WarnAbout { enum What {
4476  Nothing = 0x00,
4477  NoAssertions = 0x01,
4478  NoTests = 0x02
4479  }; };
4480 
4481  struct ShowDurations { enum OrNot {
4482  DefaultForReporter,
4483  Always,
4484  Never
4485  }; };
4486  struct RunTests { enum InWhatOrder {
4487  InDeclarationOrder,
4488  InLexicographicalOrder,
4489  InRandomOrder
4490  }; };
4491  struct UseColour { enum YesOrNo {
4492  Auto,
4493  Yes,
4494  No
4495  }; };
4496  struct WaitForKeypress { enum When {
4497  Never,
4498  BeforeStart = 1,
4499  BeforeExit = 2,
4500  BeforeStartAndExit = BeforeStart | BeforeExit
4501  }; };
4502 
4503  class TestSpec;
4504 
4506 
4507  virtual ~IConfig();
4508 
4509  virtual bool allowThrows() const = 0;
4510  virtual std::ostream& stream() const = 0;
4511  virtual std::string name() const = 0;
4512  virtual bool includeSuccessfulResults() const = 0;
4513  virtual bool shouldDebugBreak() const = 0;
4514  virtual bool warnAboutMissingAssertions() const = 0;
4515  virtual bool warnAboutNoTests() const = 0;
4516  virtual int abortAfter() const = 0;
4517  virtual bool showInvisibles() const = 0;
4518  virtual ShowDurations::OrNot showDurations() const = 0;
4519  virtual double minDuration() const = 0;
4520  virtual TestSpec const& testSpec() const = 0;
4521  virtual bool hasTestFilters() const = 0;
4522  virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4523  virtual RunTests::InWhatOrder runOrder() const = 0;
4524  virtual unsigned int rngSeed() const = 0;
4525  virtual UseColour::YesOrNo useColour() const = 0;
4526  virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4527  virtual Verbosity verbosity() const = 0;
4528 
4529  virtual bool benchmarkNoAnalysis() const = 0;
4530  virtual int benchmarkSamples() const = 0;
4531  virtual double benchmarkConfidenceInterval() const = 0;
4532  virtual unsigned int benchmarkResamples() const = 0;
4533  virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4534  };
4535 
4536  using IConfigPtr = std::shared_ptr<IConfig const>;
4537 }
4538 
4539 // end catch_interfaces_config.h
4540 // start catch_random_number_generator.h
4541 
4542 #include <cstdint>
4543 
4544 namespace Catch {
4545 
4546  // This is a simple implementation of C++11 Uniform Random Number
4547  // Generator. It does not provide all operators, because Catch2
4548  // does not use it, but it should behave as expected inside stdlib's
4549  // distributions.
4550  // The implementation is based on the PCG family (http://pcg-random.org)
4551  class SimplePcg32 {
4552  using state_type = std::uint64_t;
4553  public:
4554  using result_type = std::uint32_t;
4555  static constexpr result_type (min)() {
4556  return 0;
4557  }
4558  static constexpr result_type (max)() {
4559  return static_cast<result_type>(-1);
4560  }
4561 
4562  // Provide some default initial state for the default constructor
4563  SimplePcg32():SimplePcg32(0xed743cc4U) {}
4564 
4565  explicit SimplePcg32(result_type seed_);
4566 
4567  void seed(result_type seed_);
4568  void discard(uint64_t skip);
4569 
4570  result_type operator()();
4571 
4572  private:
4573  friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4574  friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4575 
4576  // In theory we also need operator<< and operator>>
4577  // In practice we do not use them, so we will skip them for now
4578 
4579  std::uint64_t m_state;
4580  // This part of the state determines which "stream" of the numbers
4581  // is chosen -- we take it as a constant for Catch2, so we only
4582  // need to deal with seeding the main state.
4583  // Picked by reading 8 bytes from `/dev/random` :-)
4584  static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4585  };
4586 
4587 } // end namespace Catch
4588 
4589 // end catch_random_number_generator.h
4590 #include <random>
4591 
4592 namespace Catch {
4593 namespace Generators {
4594 
4595 template <typename Float>
4596 class RandomFloatingGenerator final : public IGenerator<Float> {
4597  Catch::SimplePcg32& m_rng;
4598  std::uniform_real_distribution<Float> m_dist;
4599  Float m_current_number;
4600 public:
4601 
4602  RandomFloatingGenerator(Float a, Float b):
4603  m_rng(rng()),
4604  m_dist(a, b) {
4605  static_cast<void>(next());
4606  }
4607 
4608  Float const& get() const override {
4609  return m_current_number;
4610  }
4611  bool next() override {
4612  m_current_number = m_dist(m_rng);
4613  return true;
4614  }
4615 };
4616 
4617 template <typename Integer>
4618 class RandomIntegerGenerator final : public IGenerator<Integer> {
4619  Catch::SimplePcg32& m_rng;
4620  std::uniform_int_distribution<Integer> m_dist;
4621  Integer m_current_number;
4622 public:
4623 
4624  RandomIntegerGenerator(Integer a, Integer b):
4625  m_rng(rng()),
4626  m_dist(a, b) {
4627  static_cast<void>(next());
4628  }
4629 
4630  Integer const& get() const override {
4631  return m_current_number;
4632  }
4633  bool next() override {
4634  m_current_number = m_dist(m_rng);
4635  return true;
4636  }
4637 };
4638 
4639 // TODO: Ideally this would be also constrained against the various char types,
4640 // but I don't expect users to run into that in practice.
4641 template <typename T>
4642 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4643 GeneratorWrapper<T>>::type
4644 random(T a, T b) {
4645  return GeneratorWrapper<T>(
4646  pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4647  );
4648 }
4649 
4650 template <typename T>
4651 typename std::enable_if<std::is_floating_point<T>::value,
4652 GeneratorWrapper<T>>::type
4653 random(T a, T b) {
4654  return GeneratorWrapper<T>(
4655  pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4656  );
4657 }
4658 
4659 template <typename T>
4660 class RangeGenerator final : public IGenerator<T> {
4661  T m_current;
4662  T m_end;
4663  T m_step;
4664  bool m_positive;
4665 
4666 public:
4667  RangeGenerator(T const& start, T const& end, T const& step):
4668  m_current(start),
4669  m_end(end),
4670  m_step(step),
4671  m_positive(m_step > T(0))
4672  {
4673  assert(m_current != m_end && "Range start and end cannot be equal");
4674  assert(m_step != T(0) && "Step size cannot be zero");
4675  assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4676  }
4677 
4678  RangeGenerator(T const& start, T const& end):
4679  RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4680  {}
4681 
4682  T const& get() const override {
4683  return m_current;
4684  }
4685 
4686  bool next() override {
4687  m_current += m_step;
4688  return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4689  }
4690 };
4691 
4692 template <typename T>
4693 GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4694  static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
4695  return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4696 }
4697 
4698 template <typename T>
4699 GeneratorWrapper<T> range(T const& start, T const& end) {
4700  static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4701  return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4702 }
4703 
4704 template <typename T>
4705 class IteratorGenerator final : public IGenerator<T> {
4706  static_assert(!std::is_same<T, bool>::value,
4707  "IteratorGenerator currently does not support bools"
4708  "because of std::vector<bool> specialization");
4709 
4710  std::vector<T> m_elems;
4711  size_t m_current = 0;
4712 public:
4713  template <typename InputIterator, typename InputSentinel>
4714  IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4715  if (m_elems.empty()) {
4716  Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
4717  }
4718  }
4719 
4720  T const& get() const override {
4721  return m_elems[m_current];
4722  }
4723 
4724  bool next() override {
4725  ++m_current;
4726  return m_current != m_elems.size();
4727  }
4728 };
4729 
4730 template <typename InputIterator,
4731  typename InputSentinel,
4732  typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
4733 GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4734  return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4735 }
4736 
4737 template <typename Container,
4738  typename ResultType = typename Container::value_type>
4739 GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4740  return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4741 }
4742 
4743 } // namespace Generators
4744 } // namespace Catch
4745 
4746 // end catch_generators_specific.hpp
4747 
4748 // These files are included here so the single_include script doesn't put them
4749 // in the conditionally compiled sections
4750 // start catch_test_case_info.h
4751 
4752 #include <string>
4753 #include <vector>
4754 #include <memory>
4755 
4756 #ifdef __clang__
4757 #pragma clang diagnostic push
4758 #pragma clang diagnostic ignored "-Wpadded"
4759 #endif
4760 
4761 namespace Catch {
4762 
4763  struct ITestInvoker;
4764 
4765  struct TestCaseInfo {
4766  enum SpecialProperties{
4767  None = 0,
4768  IsHidden = 1 << 1,
4769  ShouldFail = 1 << 2,
4770  MayFail = 1 << 3,
4771  Throws = 1 << 4,
4772  NonPortable = 1 << 5,
4773  Benchmark = 1 << 6
4774  };
4775 
4776  TestCaseInfo( std::string const& _name,
4777  std::string const& _className,
4778  std::string const& _description,
4779  std::vector<std::string> const& _tags,
4780  SourceLineInfo const& _lineInfo );
4781 
4782  friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4783 
4784  bool isHidden() const;
4785  bool throws() const;
4786  bool okToFail() const;
4787  bool expectedToFail() const;
4788 
4789  std::string tagsAsString() const;
4790 
4791  std::string name;
4792  std::string className;
4793  std::string description;
4794  std::vector<std::string> tags;
4795  std::vector<std::string> lcaseTags;
4796  SourceLineInfo lineInfo;
4797  SpecialProperties properties;
4798  };
4799 
4800  class TestCase : public TestCaseInfo {
4801  public:
4802 
4803  TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4804 
4805  TestCase withName( std::string const& _newName ) const;
4806 
4807  void invoke() const;
4808 
4809  TestCaseInfo const& getTestCaseInfo() const;
4810 
4811  bool operator == ( TestCase const& other ) const;
4812  bool operator < ( TestCase const& other ) const;
4813 
4814  private:
4815  std::shared_ptr<ITestInvoker> test;
4816  };
4817 
4818  TestCase makeTestCase( ITestInvoker* testCase,
4819  std::string const& className,
4820  NameAndTags const& nameAndTags,
4821  SourceLineInfo const& lineInfo );
4822 }
4823 
4824 #ifdef __clang__
4825 #pragma clang diagnostic pop
4826 #endif
4827 
4828 // end catch_test_case_info.h
4829 // start catch_interfaces_runner.h
4830 
4831 namespace Catch {
4832 
4833  struct IRunner {
4834  virtual ~IRunner();
4835  virtual bool aborting() const = 0;
4836  };
4837 }
4838 
4839 // end catch_interfaces_runner.h
4840 
4841 #ifdef __OBJC__
4842 // start catch_objc.hpp
4843 
4844 #import <objc/runtime.h>
4845 
4846 #include <string>
4847 
4848 // NB. Any general catch headers included here must be included
4849 // in catch.hpp first to make sure they are included by the single
4850 // header for non obj-usage
4851 
4853 // This protocol is really only here for (self) documenting purposes, since
4854 // all its methods are optional.
4855 @protocol OcFixture
4856 
4857 @optional
4858 
4859 -(void) setUp;
4860 -(void) tearDown;
4861 
4862 @end
4863 
4864 namespace Catch {
4865 
4866  class OcMethod : public ITestInvoker {
4867 
4868  public:
4869  OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4870 
4871  virtual void invoke() const {
4872  id obj = [[m_cls alloc] init];
4873 
4874  performOptionalSelector( obj, @selector(setUp) );
4875  performOptionalSelector( obj, m_sel );
4876  performOptionalSelector( obj, @selector(tearDown) );
4877 
4878  arcSafeRelease( obj );
4879  }
4880  private:
4881  virtual ~OcMethod() {}
4882 
4883  Class m_cls;
4884  SEL m_sel;
4885  };
4886 
4887  namespace Detail{
4888 
4889  inline std::string getAnnotation( Class cls,
4890  std::string const& annotationName,
4891  std::string const& testCaseName ) {
4892  NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4893  SEL sel = NSSelectorFromString( selStr );
4894  arcSafeRelease( selStr );
4895  id value = performOptionalSelector( cls, sel );
4896  if( value )
4897  return [(NSString*)value UTF8String];
4898  return "";
4899  }
4900  }
4901 
4902  inline std::size_t registerTestMethods() {
4903  std::size_t noTestMethods = 0;
4904  int noClasses = objc_getClassList( nullptr, 0 );
4905 
4906  Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4907  objc_getClassList( classes, noClasses );
4908 
4909  for( int c = 0; c < noClasses; c++ ) {
4910  Class cls = classes[c];
4911  {
4912  u_int count;
4913  Method* methods = class_copyMethodList( cls, &count );
4914  for( u_int m = 0; m < count ; m++ ) {
4915  SEL selector = method_getName(methods[m]);
4916  std::string methodName = sel_getName(selector);
4917  if( startsWith( methodName, "Catch_TestCase_" ) ) {
4918  std::string testCaseName = methodName.substr( 15 );
4919  std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4920  std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4921  const char* className = class_getName( cls );
4922 
4923  getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4924  noTestMethods++;
4925  }
4926  }
4927  free(methods);
4928  }
4929  }
4930  return noTestMethods;
4931  }
4932 
4933 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4934 
4935  namespace Matchers {
4936  namespace Impl {
4937  namespace NSStringMatchers {
4938 
4939  struct StringHolder : MatcherBase<NSString*>{
4940  StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4941  StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
4942  StringHolder() {
4943  arcSafeRelease( m_substr );
4944  }
4945 
4946  bool match( NSString* str ) const override {
4947  return false;
4948  }
4949 
4950  NSString* CATCH_ARC_STRONG m_substr;
4951  };
4952 
4953  struct Equals : StringHolder {
4954  Equals( NSString* substr ) : StringHolder( substr ){}
4955 
4956  bool match( NSString* str ) const override {
4957  return (str != nil || m_substr == nil ) &&
4958  [str isEqualToString:m_substr];
4959  }
4960 
4961  std::string describe() const override {
4962  return "equals string: " + Catch::Detail::stringify( m_substr );
4963  }
4964  };
4965 
4966  struct Contains : StringHolder {
4967  Contains( NSString* substr ) : StringHolder( substr ){}
4968 
4969  bool match( NSString* str ) const override {
4970  return (str != nil || m_substr == nil ) &&
4971  [str rangeOfString:m_substr].location != NSNotFound;
4972  }
4973 
4974  std::string describe() const override {
4975  return "contains string: " + Catch::Detail::stringify( m_substr );
4976  }
4977  };
4978 
4979  struct StartsWith : StringHolder {
4980  StartsWith( NSString* substr ) : StringHolder( substr ){}
4981 
4982  bool match( NSString* str ) const override {
4983  return (str != nil || m_substr == nil ) &&
4984  [str rangeOfString:m_substr].location == 0;
4985  }
4986 
4987  std::string describe() const override {
4988  return "starts with: " + Catch::Detail::stringify( m_substr );
4989  }
4990  };
4991  struct EndsWith : StringHolder {
4992  EndsWith( NSString* substr ) : StringHolder( substr ){}
4993 
4994  bool match( NSString* str ) const override {
4995  return (str != nil || m_substr == nil ) &&
4996  [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4997  }
4998 
4999  std::string describe() const override {
5000  return "ends with: " + Catch::Detail::stringify( m_substr );
5001  }
5002  };
5003 
5004  } // namespace NSStringMatchers
5005  } // namespace Impl
5006 
5007  inline Impl::NSStringMatchers::Equals
5008  Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
5009 
5010  inline Impl::NSStringMatchers::Contains
5011  Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
5012 
5013  inline Impl::NSStringMatchers::StartsWith
5014  StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
5015 
5016  inline Impl::NSStringMatchers::EndsWith
5017  EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
5018 
5019  } // namespace Matchers
5020 
5021  using namespace Matchers;
5022 
5023 #endif // CATCH_CONFIG_DISABLE_MATCHERS
5024 
5025 } // namespace Catch
5026 
5028 #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5029 #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5030 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5031 { \
5032 return @ name; \
5033 } \
5034 +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5035 { \
5036 return @ desc; \
5037 } \
5038 -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5039 
5040 #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5041 
5042 // end catch_objc.hpp
5043 #endif
5044 
5045 // Benchmarking needs the externally-facing parts of reporters to work
5046 #if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5047 // start catch_external_interfaces.h
5048 
5049 // start catch_reporter_bases.hpp
5050 
5051 // start catch_interfaces_reporter.h
5052 
5053 // start catch_config.hpp
5054 
5055 // start catch_test_spec_parser.h
5056 
5057 #ifdef __clang__
5058 #pragma clang diagnostic push
5059 #pragma clang diagnostic ignored "-Wpadded"
5060 #endif
5061 
5062 // start catch_test_spec.h
5063 
5064 #ifdef __clang__
5065 #pragma clang diagnostic push
5066 #pragma clang diagnostic ignored "-Wpadded"
5067 #endif
5068 
5069 // start catch_wildcard_pattern.h
5070 
5071 namespace Catch
5072 {
5073  class WildcardPattern {
5074  enum WildcardPosition {
5075  NoWildcard = 0,
5076  WildcardAtStart = 1,
5077  WildcardAtEnd = 2,
5078  WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5079  };
5080 
5081  public:
5082 
5083  WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
5084  virtual ~WildcardPattern() = default;
5085  virtual bool matches( std::string const& str ) const;
5086 
5087  private:
5088  std::string normaliseString( std::string const& str ) const;
5089  CaseSensitive::Choice m_caseSensitivity;
5090  WildcardPosition m_wildcard = NoWildcard;
5091  std::string m_pattern;
5092  };
5093 }
5094 
5095 // end catch_wildcard_pattern.h
5096 #include <string>
5097 #include <vector>
5098 #include <memory>
5099 
5100 namespace Catch {
5101 
5102  struct IConfig;
5103 
5104  class TestSpec {
5105  class Pattern {
5106  public:
5107  explicit Pattern( std::string const& name );
5108  virtual ~Pattern();
5109  virtual bool matches( TestCaseInfo const& testCase ) const = 0;
5110  std::string const& name() const;
5111  private:
5112  std::string const m_name;
5113  };
5114  using PatternPtr = std::shared_ptr<Pattern>;
5115 
5116  class NamePattern : public Pattern {
5117  public:
5118  explicit NamePattern( std::string const& name, std::string const& filterString );
5119  bool matches( TestCaseInfo const& testCase ) const override;
5120  private:
5121  WildcardPattern m_wildcardPattern;
5122  };
5123 
5124  class TagPattern : public Pattern {
5125  public:
5126  explicit TagPattern( std::string const& tag, std::string const& filterString );
5127  bool matches( TestCaseInfo const& testCase ) const override;
5128  private:
5129  std::string m_tag;
5130  };
5131 
5132  class ExcludedPattern : public Pattern {
5133  public:
5134  explicit ExcludedPattern( PatternPtr const& underlyingPattern );
5135  bool matches( TestCaseInfo const& testCase ) const override;
5136  private:
5137  PatternPtr m_underlyingPattern;
5138  };
5139 
5140  struct Filter {
5141  std::vector<PatternPtr> m_patterns;
5142 
5143  bool matches( TestCaseInfo const& testCase ) const;
5144  std::string name() const;
5145  };
5146 
5147  public:
5148  struct FilterMatch {
5149  std::string name;
5150  std::vector<TestCase const*> tests;
5151  };
5152  using Matches = std::vector<FilterMatch>;
5153  using vectorStrings = std::vector<std::string>;
5154 
5155  bool hasFilters() const;
5156  bool matches( TestCaseInfo const& testCase ) const;
5157  Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
5158  const vectorStrings & getInvalidArgs() const;
5159 
5160  private:
5161  std::vector<Filter> m_filters;
5162  std::vector<std::string> m_invalidArgs;
5163  friend class TestSpecParser;
5164  };
5165 }
5166 
5167 #ifdef __clang__
5168 #pragma clang diagnostic pop
5169 #endif
5170 
5171 // end catch_test_spec.h
5172 // start catch_interfaces_tag_alias_registry.h
5173 
5174 #include <string>
5175 
5176 namespace Catch {
5177 
5178  struct TagAlias;
5179 
5180  struct ITagAliasRegistry {
5181  virtual ~ITagAliasRegistry();
5182  // Nullptr if not present
5183  virtual TagAlias const* find( std::string const& alias ) const = 0;
5184  virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
5185 
5186  static ITagAliasRegistry const& get();
5187  };
5188 
5189 } // end namespace Catch
5190 
5191 // end catch_interfaces_tag_alias_registry.h
5192 namespace Catch {
5193 
5194  class TestSpecParser {
5195  enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5196  Mode m_mode = None;
5197  Mode lastMode = None;
5198  bool m_exclusion = false;
5199  std::size_t m_pos = 0;
5200  std::size_t m_realPatternPos = 0;
5201  std::string m_arg;
5202  std::string m_substring;
5203  std::string m_patternName;
5204  std::vector<std::size_t> m_escapeChars;
5205  TestSpec::Filter m_currentFilter;
5206  TestSpec m_testSpec;
5207  ITagAliasRegistry const* m_tagAliases = nullptr;
5208 
5209  public:
5210  TestSpecParser( ITagAliasRegistry const& tagAliases );
5211 
5212  TestSpecParser& parse( std::string const& arg );
5213  TestSpec testSpec();
5214 
5215  private:
5216  bool visitChar( char c );
5217  void startNewMode( Mode mode );
5218  bool processNoneChar( char c );
5219  void processNameChar( char c );
5220  bool processOtherChar( char c );
5221  void endMode();
5222  void escape();
5223  bool isControlChar( char c ) const;
5224  void saveLastMode();
5225  void revertBackToLastMode();
5226  void addFilter();
5227  bool separate();
5228 
5229  // Handles common preprocessing of the pattern for name/tag patterns
5230  std::string preprocessPattern();
5231  // Adds the current pattern as a test name
5232  void addNamePattern();
5233  // Adds the current pattern as a tag
5234  void addTagPattern();
5235 
5236  inline void addCharToPattern(char c) {
5237  m_substring += c;
5238  m_patternName += c;
5239  m_realPatternPos++;
5240  }
5241 
5242  };
5243  TestSpec parseTestSpec( std::string const& arg );
5244 
5245 } // namespace Catch
5246 
5247 #ifdef __clang__
5248 #pragma clang diagnostic pop
5249 #endif
5250 
5251 // end catch_test_spec_parser.h
5252 // Libstdc++ doesn't like incomplete classes for unique_ptr
5253 
5254 #include <memory>
5255 #include <vector>
5256 #include <string>
5257 
5258 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
5259 #define CATCH_CONFIG_CONSOLE_WIDTH 80
5260 #endif
5261 
5262 namespace Catch {
5263 
5264  struct IStream;
5265 
5266  struct ConfigData {
5267  bool listTests = false;
5268  bool listTags = false;
5269  bool listReporters = false;
5270  bool listTestNamesOnly = false;
5271 
5272  bool showSuccessfulTests = false;
5273  bool shouldDebugBreak = false;
5274  bool noThrow = false;
5275  bool showHelp = false;
5276  bool showInvisibles = false;
5277  bool filenamesAsTags = false;
5278  bool libIdentify = false;
5279 
5280  int abortAfter = -1;
5281  unsigned int rngSeed = 0;
5282 
5283  bool benchmarkNoAnalysis = false;
5284  unsigned int benchmarkSamples = 100;
5285  double benchmarkConfidenceInterval = 0.95;
5286  unsigned int benchmarkResamples = 100000;
5287  std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5288 
5289  Verbosity verbosity = Verbosity::Normal;
5290  WarnAbout::What warnings = WarnAbout::Nothing;
5291  ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5292  double minDuration = -1;
5293  RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5294  UseColour::YesOrNo useColour = UseColour::Auto;
5295  WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5296 
5297  std::string outputFilename;
5298  std::string name;
5299  std::string processName;
5300 #ifndef CATCH_CONFIG_DEFAULT_REPORTER
5301 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
5302 #endif
5303  std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5304 #undef CATCH_CONFIG_DEFAULT_REPORTER
5305 
5306  std::vector<std::string> testsOrTags;
5307  std::vector<std::string> sectionsToRun;
5308  };
5309 
5310  class Config : public IConfig {
5311  public:
5312 
5313  Config() = default;
5314  Config( ConfigData const& data );
5315  virtual ~Config() = default;
5316 
5317  std::string const& getFilename() const;
5318 
5319  bool listTests() const;
5320  bool listTestNamesOnly() const;
5321  bool listTags() const;
5322  bool listReporters() const;
5323 
5324  std::string getProcessName() const;
5325  std::string const& getReporterName() const;
5326 
5327  std::vector<std::string> const& getTestsOrTags() const override;
5328  std::vector<std::string> const& getSectionsToRun() const override;
5329 
5330  TestSpec const& testSpec() const override;
5331  bool hasTestFilters() const override;
5332 
5333  bool showHelp() const;
5334 
5335  // IConfig interface
5336  bool allowThrows() const override;
5337  std::ostream& stream() const override;
5338  std::string name() const override;
5339  bool includeSuccessfulResults() const override;
5340  bool warnAboutMissingAssertions() const override;
5341  bool warnAboutNoTests() const override;
5342  ShowDurations::OrNot showDurations() const override;
5343  double minDuration() const override;
5344  RunTests::InWhatOrder runOrder() const override;
5345  unsigned int rngSeed() const override;
5346  UseColour::YesOrNo useColour() const override;
5347  bool shouldDebugBreak() const override;
5348  int abortAfter() const override;
5349  bool showInvisibles() const override;
5350  Verbosity verbosity() const override;
5351  bool benchmarkNoAnalysis() const override;
5352  int benchmarkSamples() const override;
5353  double benchmarkConfidenceInterval() const override;
5354  unsigned int benchmarkResamples() const override;
5355  std::chrono::milliseconds benchmarkWarmupTime() const override;
5356 
5357  private:
5358 
5359  IStream const* openStream();
5360  ConfigData m_data;
5361 
5362  std::unique_ptr<IStream const> m_stream;
5363  TestSpec m_testSpec;
5364  bool m_hasTestFilters = false;
5365  };
5366 
5367 } // end namespace Catch
5368 
5369 // end catch_config.hpp
5370 // start catch_assertionresult.h
5371 
5372 #include <string>
5373 
5374 namespace Catch {
5375 
5376  struct AssertionResultData
5377  {
5378  AssertionResultData() = delete;
5379 
5380  AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5381 
5382  std::string message;
5383  mutable std::string reconstructedExpression;
5384  LazyExpression lazyExpression;
5385  ResultWas::OfType resultType;
5386 
5387  std::string reconstructExpression() const;
5388  };
5389 
5390  class AssertionResult {
5391  public:
5392  AssertionResult() = delete;
5393  AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5394 
5395  bool isOk() const;
5396  bool succeeded() const;
5397  ResultWas::OfType getResultType() const;
5398  bool hasExpression() const;
5399  bool hasMessage() const;
5400  std::string getExpression() const;
5401  std::string getExpressionInMacro() const;
5402  bool hasExpandedExpression() const;
5403  std::string getExpandedExpression() const;
5404  std::string getMessage() const;
5405  SourceLineInfo getSourceInfo() const;
5406  StringRef getTestMacroName() const;
5407 
5408  //protected:
5409  AssertionInfo m_info;
5410  AssertionResultData m_resultData;
5411  };
5412 
5413 } // end namespace Catch
5414 
5415 // end catch_assertionresult.h
5416 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5417 // start catch_estimate.hpp
5418 
5419  // Statistics estimates
5420 
5421 
5422 namespace Catch {
5423  namespace Benchmark {
5424  template <typename Duration>
5425  struct Estimate {
5426  Duration point;
5427  Duration lower_bound;
5428  Duration upper_bound;
5429  double confidence_interval;
5430 
5431  template <typename Duration2>
5432  operator Estimate<Duration2>() const {
5433  return { point, lower_bound, upper_bound, confidence_interval };
5434  }
5435  };
5436  } // namespace Benchmark
5437 } // namespace Catch
5438 
5439 // end catch_estimate.hpp
5440 // start catch_outlier_classification.hpp
5441 
5442 // Outlier information
5443 
5444 namespace Catch {
5445  namespace Benchmark {
5446  struct OutlierClassification {
5447  int samples_seen = 0;
5448  int low_severe = 0; // more than 3 times IQR below Q1
5449  int low_mild = 0; // 1.5 to 3 times IQR below Q1
5450  int high_mild = 0; // 1.5 to 3 times IQR above Q3
5451  int high_severe = 0; // more than 3 times IQR above Q3
5452 
5453  int total() const {
5454  return low_severe + low_mild + high_mild + high_severe;
5455  }
5456  };
5457  } // namespace Benchmark
5458 } // namespace Catch
5459 
5460 // end catch_outlier_classification.hpp
5461 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5462 
5463 #include <string>
5464 #include <iosfwd>
5465 #include <map>
5466 #include <set>
5467 #include <memory>
5468 #include <algorithm>
5469 
5470 namespace Catch {
5471 
5472  struct ReporterConfig {
5473  explicit ReporterConfig( IConfigPtr const& _fullConfig );
5474 
5475  ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5476 
5477  std::ostream& stream() const;
5478  IConfigPtr fullConfig() const;
5479 
5480  private:
5481  std::ostream* m_stream;
5482  IConfigPtr m_fullConfig;
5483  };
5484 
5485  struct ReporterPreferences {
5486  bool shouldRedirectStdOut = false;
5487  bool shouldReportAllAssertions = false;
5488  };
5489 
5490  template<typename T>
5491  struct LazyStat : Option<T> {
5492  LazyStat& operator=( T const& _value ) {
5493  Option<T>::operator=( _value );
5494  used = false;
5495  return *this;
5496  }
5497  void reset() {
5498  Option<T>::reset();
5499  used = false;
5500  }
5501  bool used = false;
5502  };
5503 
5504  struct TestRunInfo {
5505  TestRunInfo( std::string const& _name );
5506  std::string name;
5507  };
5508  struct GroupInfo {
5509  GroupInfo( std::string const& _name,
5510  std::size_t _groupIndex,
5511  std::size_t _groupsCount );
5512 
5513  std::string name;
5514  std::size_t groupIndex;
5515  std::size_t groupsCounts;
5516  };
5517 
5518  struct AssertionStats {
5519  AssertionStats( AssertionResult const& _assertionResult,
5520  std::vector<MessageInfo> const& _infoMessages,
5521  Totals const& _totals );
5522 
5523  AssertionStats( AssertionStats const& ) = default;
5524  AssertionStats( AssertionStats && ) = default;
5525  AssertionStats& operator = ( AssertionStats const& ) = delete;
5526  AssertionStats& operator = ( AssertionStats && ) = delete;
5527  virtual ~AssertionStats();
5528 
5529  AssertionResult assertionResult;
5530  std::vector<MessageInfo> infoMessages;
5531  Totals totals;
5532  };
5533 
5534  struct SectionStats {
5535  SectionStats( SectionInfo const& _sectionInfo,
5536  Counts const& _assertions,
5537  double _durationInSeconds,
5538  bool _missingAssertions );
5539  SectionStats( SectionStats const& ) = default;
5540  SectionStats( SectionStats && ) = default;
5541  SectionStats& operator = ( SectionStats const& ) = default;
5542  SectionStats& operator = ( SectionStats && ) = default;
5543  virtual ~SectionStats();
5544 
5545  SectionInfo sectionInfo;
5546  Counts assertions;
5547  double durationInSeconds;
5548  bool missingAssertions;
5549  };
5550 
5551  struct TestCaseStats {
5552  TestCaseStats( TestCaseInfo const& _testInfo,
5553  Totals const& _totals,
5554  std::string const& _stdOut,
5555  std::string const& _stdErr,
5556  bool _aborting );
5557 
5558  TestCaseStats( TestCaseStats const& ) = default;
5559  TestCaseStats( TestCaseStats && ) = default;
5560  TestCaseStats& operator = ( TestCaseStats const& ) = default;
5561  TestCaseStats& operator = ( TestCaseStats && ) = default;
5562  virtual ~TestCaseStats();
5563 
5564  TestCaseInfo testInfo;
5565  Totals totals;
5566  std::string stdOut;
5567  std::string stdErr;
5568  bool aborting;
5569  };
5570 
5571  struct TestGroupStats {
5572  TestGroupStats( GroupInfo const& _groupInfo,
5573  Totals const& _totals,
5574  bool _aborting );
5575  TestGroupStats( GroupInfo const& _groupInfo );
5576 
5577  TestGroupStats( TestGroupStats const& ) = default;
5578  TestGroupStats( TestGroupStats && ) = default;
5579  TestGroupStats& operator = ( TestGroupStats const& ) = default;
5580  TestGroupStats& operator = ( TestGroupStats && ) = default;
5581  virtual ~TestGroupStats();
5582 
5583  GroupInfo groupInfo;
5584  Totals totals;
5585  bool aborting;
5586  };
5587 
5588  struct TestRunStats {
5589  TestRunStats( TestRunInfo const& _runInfo,
5590  Totals const& _totals,
5591  bool _aborting );
5592 
5593  TestRunStats( TestRunStats const& ) = default;
5594  TestRunStats( TestRunStats && ) = default;
5595  TestRunStats& operator = ( TestRunStats const& ) = default;
5596  TestRunStats& operator = ( TestRunStats && ) = default;
5597  virtual ~TestRunStats();
5598 
5599  TestRunInfo runInfo;
5600  Totals totals;
5601  bool aborting;
5602  };
5603 
5604 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5605  struct BenchmarkInfo {
5606  std::string name;
5607  double estimatedDuration;
5608  int iterations;
5609  int samples;
5610  unsigned int resamples;
5611  double clockResolution;
5612  double clockCost;
5613  };
5614 
5615  template <class Duration>
5616  struct BenchmarkStats {
5617  BenchmarkInfo info;
5618 
5619  std::vector<Duration> samples;
5620  Benchmark::Estimate<Duration> mean;
5621  Benchmark::Estimate<Duration> standardDeviation;
5622  Benchmark::OutlierClassification outliers;
5623  double outlierVariance;
5624 
5625  template <typename Duration2>
5626  operator BenchmarkStats<Duration2>() const {
5627  std::vector<Duration2> samples2;
5628  samples2.reserve(samples.size());
5629  std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5630  return {
5631  info,
5632  std::move(samples2),
5633  mean,
5634  standardDeviation,
5635  outliers,
5636  outlierVariance,
5637  };
5638  }
5639  };
5640 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5641 
5642  struct IStreamingReporter {
5643  virtual ~IStreamingReporter() = default;
5644 
5645  // Implementing class must also provide the following static methods:
5646  // static std::string getDescription();
5647  // static std::set<Verbosity> getSupportedVerbosities()
5648 
5649  virtual ReporterPreferences getPreferences() const = 0;
5650 
5651  virtual void noMatchingTestCases( std::string const& spec ) = 0;
5652 
5653  virtual void reportInvalidArguments(std::string const&) {}
5654 
5655  virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5656  virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5657 
5658  virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5659  virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5660 
5661 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5662  virtual void benchmarkPreparing( std::string const& ) {}
5663  virtual void benchmarkStarting( BenchmarkInfo const& ) {}
5664  virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
5665  virtual void benchmarkFailed( std::string const& ) {}
5666 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5667 
5668  virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5669 
5670  // The return value indicates if the messages buffer should be cleared:
5671  virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5672 
5673  virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5674  virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5675  virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5676  virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5677 
5678  virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5679 
5680  // Default empty implementation provided
5681  virtual void fatalErrorEncountered( StringRef name );
5682 
5683  virtual bool isMulti() const;
5684  };
5685  using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5686 
5687  struct IReporterFactory {
5688  virtual ~IReporterFactory();
5689  virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5690  virtual std::string getDescription() const = 0;
5691  };
5692  using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5693 
5694  struct IReporterRegistry {
5695  using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5696  using Listeners = std::vector<IReporterFactoryPtr>;
5697 
5698  virtual ~IReporterRegistry();
5699  virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5700  virtual FactoryMap const& getFactories() const = 0;
5701  virtual Listeners const& getListeners() const = 0;
5702  };
5703 
5704 } // end namespace Catch
5705 
5706 // end catch_interfaces_reporter.h
5707 #include <algorithm>
5708 #include <cstring>
5709 #include <cfloat>
5710 #include <cstdio>
5711 #include <cassert>
5712 #include <memory>
5713 #include <ostream>
5714 
5715 namespace Catch {
5716  void prepareExpandedExpression(AssertionResult& result);
5717 
5718  // Returns double formatted as %.3f (format expected on output)
5719  std::string getFormattedDuration( double duration );
5720 
5722  bool shouldShowDuration( IConfig const& config, double duration );
5723 
5724  std::string serializeFilters( std::vector<std::string> const& container );
5725 
5726  template<typename DerivedT>
5727  struct StreamingReporterBase : IStreamingReporter {
5728 
5729  StreamingReporterBase( ReporterConfig const& _config )
5730  : m_config( _config.fullConfig() ),
5731  stream( _config.stream() )
5732  {
5733  m_reporterPrefs.shouldRedirectStdOut = false;
5734  if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5735  CATCH_ERROR( "Verbosity level not supported by this reporter" );
5736  }
5737 
5738  ReporterPreferences getPreferences() const override {
5739  return m_reporterPrefs;
5740  }
5741 
5742  static std::set<Verbosity> getSupportedVerbosities() {
5743  return { Verbosity::Normal };
5744  }
5745 
5746  ~StreamingReporterBase() override = default;
5747 
5748  void noMatchingTestCases(std::string const&) override {}
5749 
5750  void reportInvalidArguments(std::string const&) override {}
5751 
5752  void testRunStarting(TestRunInfo const& _testRunInfo) override {
5753  currentTestRunInfo = _testRunInfo;
5754  }
5755 
5756  void testGroupStarting(GroupInfo const& _groupInfo) override {
5757  currentGroupInfo = _groupInfo;
5758  }
5759 
5760  void testCaseStarting(TestCaseInfo const& _testInfo) override {
5761  currentTestCaseInfo = _testInfo;
5762  }
5763  void sectionStarting(SectionInfo const& _sectionInfo) override {
5764  m_sectionStack.push_back(_sectionInfo);
5765  }
5766 
5767  void sectionEnded(SectionStats const& /* _sectionStats */) override {
5768  m_sectionStack.pop_back();
5769  }
5770  void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5771  currentTestCaseInfo.reset();
5772  }
5773  void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5774  currentGroupInfo.reset();
5775  }
5776  void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5777  currentTestCaseInfo.reset();
5778  currentGroupInfo.reset();
5779  currentTestRunInfo.reset();
5780  }
5781 
5782  void skipTest(TestCaseInfo const&) override {
5783  // Don't do anything with this by default.
5784  // It can optionally be overridden in the derived class.
5785  }
5786 
5787  IConfigPtr m_config;
5788  std::ostream& stream;
5789 
5790  LazyStat<TestRunInfo> currentTestRunInfo;
5791  LazyStat<GroupInfo> currentGroupInfo;
5792  LazyStat<TestCaseInfo> currentTestCaseInfo;
5793 
5794  std::vector<SectionInfo> m_sectionStack;
5795  ReporterPreferences m_reporterPrefs;
5796  };
5797 
5798  template<typename DerivedT>
5799  struct CumulativeReporterBase : IStreamingReporter {
5800  template<typename T, typename ChildNodeT>
5801  struct Node {
5802  explicit Node( T const& _value ) : value( _value ) {}
5803  virtual ~Node() {}
5804 
5805  using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5806  T value;
5807  ChildNodes children;
5808  };
5809  struct SectionNode {
5810  explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5811  virtual ~SectionNode() = default;
5812 
5813  bool operator == (SectionNode const& other) const {
5814  return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5815  }
5816  bool operator == (std::shared_ptr<SectionNode> const& other) const {
5817  return operator==(*other);
5818  }
5819 
5820  SectionStats stats;
5821  using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5822  using Assertions = std::vector<AssertionStats>;
5823  ChildSections childSections;
5824  Assertions assertions;
5825  std::string stdOut;
5826  std::string stdErr;
5827  };
5828 
5829  struct BySectionInfo {
5830  BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
5831  BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
5832  bool operator() (std::shared_ptr<SectionNode> const& node) const {
5833  return ((node->stats.sectionInfo.name == m_other.name) &&
5834  (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5835  }
5836  void operator=(BySectionInfo const&) = delete;
5837 
5838  private:
5839  SectionInfo const& m_other;
5840  };
5841 
5842  using TestCaseNode = Node<TestCaseStats, SectionNode>;
5843  using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5844  using TestRunNode = Node<TestRunStats, TestGroupNode>;
5845 
5846  CumulativeReporterBase( ReporterConfig const& _config )
5847  : m_config( _config.fullConfig() ),
5848  stream( _config.stream() )
5849  {
5850  m_reporterPrefs.shouldRedirectStdOut = false;
5851  if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5852  CATCH_ERROR( "Verbosity level not supported by this reporter" );
5853  }
5854  ~CumulativeReporterBase() override = default;
5855 
5856  ReporterPreferences getPreferences() const override {
5857  return m_reporterPrefs;
5858  }
5859 
5860  static std::set<Verbosity> getSupportedVerbosities() {
5861  return { Verbosity::Normal };
5862  }
5863 
5864  void testRunStarting( TestRunInfo const& ) override {}
5865  void testGroupStarting( GroupInfo const& ) override {}
5866 
5867  void testCaseStarting( TestCaseInfo const& ) override {}
5868 
5869  void sectionStarting( SectionInfo const& sectionInfo ) override {
5870  SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5871  std::shared_ptr<SectionNode> node;
5872  if( m_sectionStack.empty() ) {
5873  if( !m_rootSection )
5874  m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5875  node = m_rootSection;
5876  }
5877  else {
5878  SectionNode& parentNode = *m_sectionStack.back();
5879  auto it =
5880  std::find_if( parentNode.childSections.begin(),
5881  parentNode.childSections.end(),
5882  BySectionInfo( sectionInfo ) );
5883  if( it == parentNode.childSections.end() ) {
5884  node = std::make_shared<SectionNode>( incompleteStats );
5885  parentNode.childSections.push_back( node );
5886  }
5887  else
5888  node = *it;
5889  }
5890  m_sectionStack.push_back( node );
5891  m_deepestSection = std::move(node);
5892  }
5893 
5894  void assertionStarting(AssertionInfo const&) override {}
5895 
5896  bool assertionEnded(AssertionStats const& assertionStats) override {
5897  assert(!m_sectionStack.empty());
5898  // AssertionResult holds a pointer to a temporary DecomposedExpression,
5899  // which getExpandedExpression() calls to build the expression string.
5900  // Our section stack copy of the assertionResult will likely outlive the
5901  // temporary, so it must be expanded or discarded now to avoid calling
5902  // a destroyed object later.
5903  prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5904  SectionNode& sectionNode = *m_sectionStack.back();
5905  sectionNode.assertions.push_back(assertionStats);
5906  return true;
5907  }
5908  void sectionEnded(SectionStats const& sectionStats) override {
5909  assert(!m_sectionStack.empty());
5910  SectionNode& node = *m_sectionStack.back();
5911  node.stats = sectionStats;
5912  m_sectionStack.pop_back();
5913  }
5914  void testCaseEnded(TestCaseStats const& testCaseStats) override {
5915  auto node = std::make_shared<TestCaseNode>(testCaseStats);
5916  assert(m_sectionStack.size() == 0);
5917  node->children.push_back(m_rootSection);
5918  m_testCases.push_back(node);
5919  m_rootSection.reset();
5920 
5921  assert(m_deepestSection);
5922  m_deepestSection->stdOut = testCaseStats.stdOut;
5923  m_deepestSection->stdErr = testCaseStats.stdErr;
5924  }
5925  void testGroupEnded(TestGroupStats const& testGroupStats) override {
5926  auto node = std::make_shared<TestGroupNode>(testGroupStats);
5927  node->children.swap(m_testCases);
5928  m_testGroups.push_back(node);
5929  }
5930  void testRunEnded(TestRunStats const& testRunStats) override {
5931  auto node = std::make_shared<TestRunNode>(testRunStats);
5932  node->children.swap(m_testGroups);
5933  m_testRuns.push_back(node);
5934  testRunEndedCumulative();
5935  }
5936  virtual void testRunEndedCumulative() = 0;
5937 
5938  void skipTest(TestCaseInfo const&) override {}
5939 
5940  IConfigPtr m_config;
5941  std::ostream& stream;
5942  std::vector<AssertionStats> m_assertions;
5943  std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5944  std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5945  std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5946 
5947  std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5948 
5949  std::shared_ptr<SectionNode> m_rootSection;
5950  std::shared_ptr<SectionNode> m_deepestSection;
5951  std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5952  ReporterPreferences m_reporterPrefs;
5953  };
5954 
5955  template<char C>
5956  char const* getLineOfChars() {
5957  static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5958  if( !*line ) {
5959  std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5960  line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5961  }
5962  return line;
5963  }
5964 
5965  struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5966  TestEventListenerBase( ReporterConfig const& _config );
5967 
5968  static std::set<Verbosity> getSupportedVerbosities();
5969 
5970  void assertionStarting(AssertionInfo const&) override;
5971  bool assertionEnded(AssertionStats const&) override;
5972  };
5973 
5974 } // end namespace Catch
5975 
5976 // end catch_reporter_bases.hpp
5977 // start catch_console_colour.h
5978 
5979 namespace Catch {
5980 
5981  struct Colour {
5982  enum Code {
5983  None = 0,
5984 
5985  White,
5986  Red,
5987  Green,
5988  Blue,
5989  Cyan,
5990  Yellow,
5991  Grey,
5992 
5993  Bright = 0x10,
5994 
5995  BrightRed = Bright | Red,
5996  BrightGreen = Bright | Green,
5997  LightGrey = Bright | Grey,
5998  BrightWhite = Bright | White,
5999  BrightYellow = Bright | Yellow,
6000 
6001  // By intention
6002  FileName = LightGrey,
6003  Warning = BrightYellow,
6004  ResultError = BrightRed,
6005  ResultSuccess = BrightGreen,
6006  ResultExpectedFailure = Warning,
6007 
6008  Error = BrightRed,
6009  Success = Green,
6010 
6011  OriginalExpression = Cyan,
6012  ReconstructedExpression = BrightYellow,
6013 
6014  SecondaryText = LightGrey,
6015  Headers = White
6016  };
6017 
6018  // Use constructed object for RAII guard
6019  Colour( Code _colourCode );
6020  Colour( Colour&& other ) noexcept;
6021  Colour& operator=( Colour&& other ) noexcept;
6022  ~Colour();
6023 
6024  // Use static method for one-shot changes
6025  static void use( Code _colourCode );
6026 
6027  private:
6028  bool m_moved = false;
6029  };
6030 
6031  std::ostream& operator << ( std::ostream& os, Colour const& );
6032 
6033 } // end namespace Catch
6034 
6035 // end catch_console_colour.h
6036 // start catch_reporter_registrars.hpp
6037 
6038 
6039 namespace Catch {
6040 
6041  template<typename T>
6042  class ReporterRegistrar {
6043 
6044  class ReporterFactory : public IReporterFactory {
6045 
6046  IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6047  return std::unique_ptr<T>( new T( config ) );
6048  }
6049 
6050  std::string getDescription() const override {
6051  return T::getDescription();
6052  }
6053  };
6054 
6055  public:
6056 
6057  explicit ReporterRegistrar( std::string const& name ) {
6058  getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6059  }
6060  };
6061 
6062  template<typename T>
6063  class ListenerRegistrar {
6064 
6065  class ListenerFactory : public IReporterFactory {
6066 
6067  IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6068  return std::unique_ptr<T>( new T( config ) );
6069  }
6070  std::string getDescription() const override {
6071  return std::string();
6072  }
6073  };
6074 
6075  public:
6076 
6077  ListenerRegistrar() {
6078  getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6079  }
6080  };
6081 }
6082 
6083 #if !defined(CATCH_CONFIG_DISABLE)
6084 
6085 #define CATCH_REGISTER_REPORTER( name, reporterType ) \
6086  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6087  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6088  namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6089  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6090 
6091 #define CATCH_REGISTER_LISTENER( listenerType ) \
6092  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6093  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6094  namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6095  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6096 #else // CATCH_CONFIG_DISABLE
6097 
6098 #define CATCH_REGISTER_REPORTER(name, reporterType)
6099 #define CATCH_REGISTER_LISTENER(listenerType)
6100 
6101 #endif // CATCH_CONFIG_DISABLE
6102 
6103 // end catch_reporter_registrars.hpp
6104 // Allow users to base their work off existing reporters
6105 // start catch_reporter_compact.h
6106 
6107 namespace Catch {
6108 
6109  struct CompactReporter : StreamingReporterBase<CompactReporter> {
6110 
6111  using StreamingReporterBase::StreamingReporterBase;
6112 
6113  ~CompactReporter() override;
6114 
6115  static std::string getDescription();
6116 
6117  void noMatchingTestCases(std::string const& spec) override;
6118 
6119  void assertionStarting(AssertionInfo const&) override;
6120 
6121  bool assertionEnded(AssertionStats const& _assertionStats) override;
6122 
6123  void sectionEnded(SectionStats const& _sectionStats) override;
6124 
6125  void testRunEnded(TestRunStats const& _testRunStats) override;
6126 
6127  };
6128 
6129 } // end namespace Catch
6130 
6131 // end catch_reporter_compact.h
6132 // start catch_reporter_console.h
6133 
6134 #if defined(_MSC_VER)
6135 #pragma warning(push)
6136 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6137  // Note that 4062 (not all labels are handled
6138  // and default is missing) is enabled
6139 #endif
6140 
6141 namespace Catch {
6142  // Fwd decls
6143  struct SummaryColumn;
6144  class TablePrinter;
6145 
6146  struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6147  std::unique_ptr<TablePrinter> m_tablePrinter;
6148 
6149  ConsoleReporter(ReporterConfig const& config);
6150  ~ConsoleReporter() override;
6151  static std::string getDescription();
6152 
6153  void noMatchingTestCases(std::string const& spec) override;
6154 
6155  void reportInvalidArguments(std::string const&arg) override;
6156 
6157  void assertionStarting(AssertionInfo const&) override;
6158 
6159  bool assertionEnded(AssertionStats const& _assertionStats) override;
6160 
6161  void sectionStarting(SectionInfo const& _sectionInfo) override;
6162  void sectionEnded(SectionStats const& _sectionStats) override;
6163 
6164 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6165  void benchmarkPreparing(std::string const& name) override;
6166  void benchmarkStarting(BenchmarkInfo const& info) override;
6167  void benchmarkEnded(BenchmarkStats<> const& stats) override;
6168  void benchmarkFailed(std::string const& error) override;
6169 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6170 
6171  void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6172  void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6173  void testRunEnded(TestRunStats const& _testRunStats) override;
6174  void testRunStarting(TestRunInfo const& _testRunInfo) override;
6175  private:
6176 
6177  void lazyPrint();
6178 
6179  void lazyPrintWithoutClosingBenchmarkTable();
6180  void lazyPrintRunInfo();
6181  void lazyPrintGroupInfo();
6182  void printTestCaseAndSectionHeader();
6183 
6184  void printClosedHeader(std::string const& _name);
6185  void printOpenHeader(std::string const& _name);
6186 
6187  // if string has a : in first line will set indent to follow it on
6188  // subsequent lines
6189  void printHeaderString(std::string const& _string, std::size_t indent = 0);
6190 
6191  void printTotals(Totals const& totals);
6192  void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
6193 
6194  void printTotalsDivider(Totals const& totals);
6195  void printSummaryDivider();
6196  void printTestFilters();
6197 
6198  private:
6199  bool m_headerPrinted = false;
6200  };
6201 
6202 } // end namespace Catch
6203 
6204 #if defined(_MSC_VER)
6205 #pragma warning(pop)
6206 #endif
6207 
6208 // end catch_reporter_console.h
6209 // start catch_reporter_junit.h
6210 
6211 // start catch_xmlwriter.h
6212 
6213 #include <vector>
6214 
6215 namespace Catch {
6216  enum class XmlFormatting {
6217  None = 0x00,
6218  Indent = 0x01,
6219  Newline = 0x02,
6220  };
6221 
6222  XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6223  XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6224 
6225  class XmlEncode {
6226  public:
6227  enum ForWhat { ForTextNodes, ForAttributes };
6228 
6229  XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6230 
6231  void encodeTo( std::ostream& os ) const;
6232 
6233  friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6234 
6235  private:
6236  std::string m_str;
6237  ForWhat m_forWhat;
6238  };
6239 
6240  class XmlWriter {
6241  public:
6242 
6243  class ScopedElement {
6244  public:
6245  ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6246 
6247  ScopedElement( ScopedElement&& other ) noexcept;
6248  ScopedElement& operator=( ScopedElement&& other ) noexcept;
6249 
6250  ~ScopedElement();
6251 
6252  ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6253 
6254  template<typename T>
6255  ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6256  m_writer->writeAttribute( name, attribute );
6257  return *this;
6258  }
6259 
6260  private:
6261  mutable XmlWriter* m_writer = nullptr;
6262  XmlFormatting m_fmt;
6263  };
6264 
6265  XmlWriter( std::ostream& os = Catch::cout() );
6266  ~XmlWriter();
6267 
6268  XmlWriter( XmlWriter const& ) = delete;
6269  XmlWriter& operator=( XmlWriter const& ) = delete;
6270 
6271  XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6272 
6273  ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6274 
6275  XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6276 
6277  XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6278 
6279  XmlWriter& writeAttribute( std::string const& name, bool attribute );
6280 
6281  template<typename T>
6282  XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6284  rss << attribute;
6285  return writeAttribute( name, rss.str() );
6286  }
6287 
6288  XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6289 
6290  XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6291 
6292  void writeStylesheetRef( std::string const& url );
6293 
6294  XmlWriter& writeBlankLine();
6295 
6296  void ensureTagClosed();
6297 
6298  private:
6299 
6300  void applyFormatting(XmlFormatting fmt);
6301 
6302  void writeDeclaration();
6303 
6304  void newlineIfNecessary();
6305 
6306  bool m_tagIsOpen = false;
6307  bool m_needsNewline = false;
6308  std::vector<std::string> m_tags;
6309  std::string m_indent;
6310  std::ostream& m_os;
6311  };
6312 
6313 }
6314 
6315 // end catch_xmlwriter.h
6316 namespace Catch {
6317 
6318  class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6319  public:
6320  JunitReporter(ReporterConfig const& _config);
6321 
6322  ~JunitReporter() override;
6323 
6324  static std::string getDescription();
6325 
6326  void noMatchingTestCases(std::string const& /*spec*/) override;
6327 
6328  void testRunStarting(TestRunInfo const& runInfo) override;
6329 
6330  void testGroupStarting(GroupInfo const& groupInfo) override;
6331 
6332  void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6333  bool assertionEnded(AssertionStats const& assertionStats) override;
6334 
6335  void testCaseEnded(TestCaseStats const& testCaseStats) override;
6336 
6337  void testGroupEnded(TestGroupStats const& testGroupStats) override;
6338 
6339  void testRunEndedCumulative() override;
6340 
6341  void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6342 
6343  void writeTestCase(TestCaseNode const& testCaseNode);
6344 
6345  void writeSection(std::string const& className,
6346  std::string const& rootName,
6347  SectionNode const& sectionNode);
6348 
6349  void writeAssertions(SectionNode const& sectionNode);
6350  void writeAssertion(AssertionStats const& stats);
6351 
6352  XmlWriter xml;
6353  Timer suiteTimer;
6354  std::string stdOutForSuite;
6355  std::string stdErrForSuite;
6356  unsigned int unexpectedExceptions = 0;
6357  bool m_okToFail = false;
6358  };
6359 
6360 } // end namespace Catch
6361 
6362 // end catch_reporter_junit.h
6363 // start catch_reporter_xml.h
6364 
6365 namespace Catch {
6366  class XmlReporter : public StreamingReporterBase<XmlReporter> {
6367  public:
6368  XmlReporter(ReporterConfig const& _config);
6369 
6370  ~XmlReporter() override;
6371 
6372  static std::string getDescription();
6373 
6374  virtual std::string getStylesheetRef() const;
6375 
6376  void writeSourceInfo(SourceLineInfo const& sourceInfo);
6377 
6378  public: // StreamingReporterBase
6379 
6380  void noMatchingTestCases(std::string const& s) override;
6381 
6382  void testRunStarting(TestRunInfo const& testInfo) override;
6383 
6384  void testGroupStarting(GroupInfo const& groupInfo) override;
6385 
6386  void testCaseStarting(TestCaseInfo const& testInfo) override;
6387 
6388  void sectionStarting(SectionInfo const& sectionInfo) override;
6389 
6390  void assertionStarting(AssertionInfo const&) override;
6391 
6392  bool assertionEnded(AssertionStats const& assertionStats) override;
6393 
6394  void sectionEnded(SectionStats const& sectionStats) override;
6395 
6396  void testCaseEnded(TestCaseStats const& testCaseStats) override;
6397 
6398  void testGroupEnded(TestGroupStats const& testGroupStats) override;
6399 
6400  void testRunEnded(TestRunStats const& testRunStats) override;
6401 
6402 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6403  void benchmarkPreparing(std::string const& name) override;
6404  void benchmarkStarting(BenchmarkInfo const&) override;
6405  void benchmarkEnded(BenchmarkStats<> const&) override;
6406  void benchmarkFailed(std::string const&) override;
6407 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6408 
6409  private:
6410  Timer m_testCaseTimer;
6411  XmlWriter m_xml;
6412  int m_sectionDepth = 0;
6413  };
6414 
6415 } // end namespace Catch
6416 
6417 // end catch_reporter_xml.h
6418 
6419 // end catch_external_interfaces.h
6420 #endif
6421 
6422 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6423 // start catch_benchmarking_all.hpp
6424 
6425 // A proxy header that includes all of the benchmarking headers to allow
6426 // concise include of the benchmarking features. You should prefer the
6427 // individual includes in standard use.
6428 
6429 // start catch_benchmark.hpp
6430 
6431  // Benchmark
6432 
6433 // start catch_chronometer.hpp
6434 
6435 // User-facing chronometer
6436 
6437 
6438 // start catch_clock.hpp
6439 
6440 // Clocks
6441 
6442 
6443 #include <chrono>
6444 #include <ratio>
6445 
6446 namespace Catch {
6447  namespace Benchmark {
6448  template <typename Clock>
6449  using ClockDuration = typename Clock::duration;
6450  template <typename Clock>
6451  using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6452 
6453  template <typename Clock>
6454  using TimePoint = typename Clock::time_point;
6455 
6456  using default_clock = std::chrono::steady_clock;
6457 
6458  template <typename Clock>
6459  struct now {
6460  TimePoint<Clock> operator()() const {
6461  return Clock::now();
6462  }
6463  };
6464 
6465  using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6466  } // namespace Benchmark
6467 } // namespace Catch
6468 
6469 // end catch_clock.hpp
6470 // start catch_optimizer.hpp
6471 
6472  // Hinting the optimizer
6473 
6474 
6475 #if defined(_MSC_VER)
6476 # include <atomic> // atomic_thread_fence
6477 #endif
6478 
6479 namespace Catch {
6480  namespace Benchmark {
6481 #if defined(__GNUC__) || defined(__clang__)
6482  template <typename T>
6483  inline void keep_memory(T* p) {
6484  asm volatile("" : : "g"(p) : "memory");
6485  }
6486  inline void keep_memory() {
6487  asm volatile("" : : : "memory");
6488  }
6489 
6490  namespace Detail {
6491  inline void optimizer_barrier() { keep_memory(); }
6492  } // namespace Detail
6493 #elif defined(_MSC_VER)
6494 
6495 #pragma optimize("", off)
6496  template <typename T>
6497  inline void keep_memory(T* p) {
6498  // thanks @milleniumbug
6499  *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6500  }
6501  // TODO equivalent keep_memory()
6502 #pragma optimize("", on)
6503 
6504  namespace Detail {
6505  inline void optimizer_barrier() {
6506  std::atomic_thread_fence(std::memory_order_seq_cst);
6507  }
6508  } // namespace Detail
6509 
6510 #endif
6511 
6512  template <typename T>
6513  inline void deoptimize_value(T&& x) {
6514  keep_memory(&x);
6515  }
6516 
6517  template <typename Fn, typename... Args>
6518  inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6519  deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6520  }
6521 
6522  template <typename Fn, typename... Args>
6523  inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6524  std::forward<Fn>(fn) (std::forward<Args...>(args...));
6525  }
6526  } // namespace Benchmark
6527 } // namespace Catch
6528 
6529 // end catch_optimizer.hpp
6530 // start catch_complete_invoke.hpp
6531 
6532 // Invoke with a special case for void
6533 
6534 
6535 #include <type_traits>
6536 #include <utility>
6537 
6538 namespace Catch {
6539  namespace Benchmark {
6540  namespace Detail {
6541  template <typename T>
6542  struct CompleteType { using type = T; };
6543  template <>
6544  struct CompleteType<void> { struct type {}; };
6545 
6546  template <typename T>
6547  using CompleteType_t = typename CompleteType<T>::type;
6548 
6549  template <typename Result>
6550  struct CompleteInvoker {
6551  template <typename Fun, typename... Args>
6552  static Result invoke(Fun&& fun, Args&&... args) {
6553  return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6554  }
6555  };
6556  template <>
6557  struct CompleteInvoker<void> {
6558  template <typename Fun, typename... Args>
6559  static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6560  std::forward<Fun>(fun)(std::forward<Args>(args)...);
6561  return {};
6562  }
6563  };
6564 
6565  // invoke and not return void :(
6566  template <typename Fun, typename... Args>
6567  CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6568  return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6569  }
6570 
6571  const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6572  } // namespace Detail
6573 
6574  template <typename Fun>
6575  Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6576  CATCH_TRY{
6577  return Detail::complete_invoke(std::forward<Fun>(fun));
6578  } CATCH_CATCH_ALL{
6579  getResultCapture().benchmarkFailed(translateActiveException());
6580  CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6581  }
6582  }
6583  } // namespace Benchmark
6584 } // namespace Catch
6585 
6586 // end catch_complete_invoke.hpp
6587 namespace Catch {
6588  namespace Benchmark {
6589  namespace Detail {
6590  struct ChronometerConcept {
6591  virtual void start() = 0;
6592  virtual void finish() = 0;
6593  virtual ~ChronometerConcept() = default;
6594  };
6595  template <typename Clock>
6596  struct ChronometerModel final : public ChronometerConcept {
6597  void start() override { started = Clock::now(); }
6598  void finish() override { finished = Clock::now(); }
6599 
6600  ClockDuration<Clock> elapsed() const { return finished - started; }
6601 
6602  TimePoint<Clock> started;
6603  TimePoint<Clock> finished;
6604  };
6605  } // namespace Detail
6606 
6607  struct Chronometer {
6608  public:
6609  template <typename Fun>
6610  void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6611 
6612  int runs() const { return k; }
6613 
6614  Chronometer(Detail::ChronometerConcept& meter, int k)
6615  : impl(&meter)
6616  , k(k) {}
6617 
6618  private:
6619  template <typename Fun>
6620  void measure(Fun&& fun, std::false_type) {
6621  measure([&fun](int) { return fun(); }, std::true_type());
6622  }
6623 
6624  template <typename Fun>
6625  void measure(Fun&& fun, std::true_type) {
6626  Detail::optimizer_barrier();
6627  impl->start();
6628  for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6629  impl->finish();
6630  Detail::optimizer_barrier();
6631  }
6632 
6633  Detail::ChronometerConcept* impl;
6634  int k;
6635  };
6636  } // namespace Benchmark
6637 } // namespace Catch
6638 
6639 // end catch_chronometer.hpp
6640 // start catch_environment.hpp
6641 
6642 // Environment information
6643 
6644 
6645 namespace Catch {
6646  namespace Benchmark {
6647  template <typename Duration>
6648  struct EnvironmentEstimate {
6649  Duration mean;
6650  OutlierClassification outliers;
6651 
6652  template <typename Duration2>
6653  operator EnvironmentEstimate<Duration2>() const {
6654  return { mean, outliers };
6655  }
6656  };
6657  template <typename Clock>
6658  struct Environment {
6659  using clock_type = Clock;
6660  EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6661  EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6662  };
6663  } // namespace Benchmark
6664 } // namespace Catch
6665 
6666 // end catch_environment.hpp
6667 // start catch_execution_plan.hpp
6668 
6669  // Execution plan
6670 
6671 
6672 // start catch_benchmark_function.hpp
6673 
6674  // Dumb std::function implementation for consistent call overhead
6675 
6676 
6677 #include <cassert>
6678 #include <type_traits>
6679 #include <utility>
6680 #include <memory>
6681 
6682 namespace Catch {
6683  namespace Benchmark {
6684  namespace Detail {
6685  template <typename T>
6686  using Decay = typename std::decay<T>::type;
6687  template <typename T, typename U>
6688  struct is_related
6689  : std::is_same<Decay<T>, Decay<U>> {};
6690 
6698  struct BenchmarkFunction {
6699  private:
6700  struct callable {
6701  virtual void call(Chronometer meter) const = 0;
6702  virtual callable* clone() const = 0;
6703  virtual ~callable() = default;
6704  };
6705  template <typename Fun>
6706  struct model : public callable {
6707  model(Fun&& fun) : fun(std::move(fun)) {}
6708  model(Fun const& fun) : fun(fun) {}
6709 
6710  model<Fun>* clone() const override { return new model<Fun>(*this); }
6711 
6712  void call(Chronometer meter) const override {
6713  call(meter, is_callable<Fun(Chronometer)>());
6714  }
6715  void call(Chronometer meter, std::true_type) const {
6716  fun(meter);
6717  }
6718  void call(Chronometer meter, std::false_type) const {
6719  meter.measure(fun);
6720  }
6721 
6722  Fun fun;
6723  };
6724 
6725  struct do_nothing { void operator()() const {} };
6726 
6727  template <typename T>
6728  BenchmarkFunction(model<T>* c) : f(c) {}
6729 
6730  public:
6731  BenchmarkFunction()
6732  : f(new model<do_nothing>{ {} }) {}
6733 
6734  template <typename Fun,
6735  typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
6736  BenchmarkFunction(Fun&& fun)
6737  : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6738 
6739  BenchmarkFunction(BenchmarkFunction&& that)
6740  : f(std::move(that.f)) {}
6741 
6742  BenchmarkFunction(BenchmarkFunction const& that)
6743  : f(that.f->clone()) {}
6744 
6745  BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6746  f = std::move(that.f);
6747  return *this;
6748  }
6749 
6750  BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6751  f.reset(that.f->clone());
6752  return *this;
6753  }
6754 
6755  void operator()(Chronometer meter) const { f->call(meter); }
6756 
6757  private:
6758  std::unique_ptr<callable> f;
6759  };
6760  } // namespace Detail
6761  } // namespace Benchmark
6762 } // namespace Catch
6763 
6764 // end catch_benchmark_function.hpp
6765 // start catch_repeat.hpp
6766 
6767 // repeat algorithm
6768 
6769 
6770 #include <type_traits>
6771 #include <utility>
6772 
6773 namespace Catch {
6774  namespace Benchmark {
6775  namespace Detail {
6776  template <typename Fun>
6777  struct repeater {
6778  void operator()(int k) const {
6779  for (int i = 0; i < k; ++i) {
6780  fun();
6781  }
6782  }
6783  Fun fun;
6784  };
6785  template <typename Fun>
6786  repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6787  return { std::forward<Fun>(fun) };
6788  }
6789  } // namespace Detail
6790  } // namespace Benchmark
6791 } // namespace Catch
6792 
6793 // end catch_repeat.hpp
6794 // start catch_run_for_at_least.hpp
6795 
6796 // Run a function for a minimum amount of time
6797 
6798 
6799 // start catch_measure.hpp
6800 
6801 // Measure
6802 
6803 
6804 // start catch_timing.hpp
6805 
6806 // Timing
6807 
6808 
6809 #include <tuple>
6810 #include <type_traits>
6811 
6812 namespace Catch {
6813  namespace Benchmark {
6814  template <typename Duration, typename Result>
6815  struct Timing {
6816  Duration elapsed;
6817  Result result;
6818  int iterations;
6819  };
6820  template <typename Clock, typename Func, typename... Args>
6821  using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6822  } // namespace Benchmark
6823 } // namespace Catch
6824 
6825 // end catch_timing.hpp
6826 #include <utility>
6827 
6828 namespace Catch {
6829  namespace Benchmark {
6830  namespace Detail {
6831  template <typename Clock, typename Fun, typename... Args>
6832  TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6833  auto start = Clock::now();
6834  auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6835  auto end = Clock::now();
6836  auto delta = end - start;
6837  return { delta, std::forward<decltype(r)>(r), 1 };
6838  }
6839  } // namespace Detail
6840  } // namespace Benchmark
6841 } // namespace Catch
6842 
6843 // end catch_measure.hpp
6844 #include <utility>
6845 #include <type_traits>
6846 
6847 namespace Catch {
6848  namespace Benchmark {
6849  namespace Detail {
6850  template <typename Clock, typename Fun>
6851  TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6852  return Detail::measure<Clock>(fun, iters);
6853  }
6854  template <typename Clock, typename Fun>
6855  TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6856  Detail::ChronometerModel<Clock> meter;
6857  auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6858 
6859  return { meter.elapsed(), std::move(result), iters };
6860  }
6861 
6862  template <typename Clock, typename Fun>
6863  using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6864 
6865  struct optimized_away_error : std::exception {
6866  const char* what() const noexcept override {
6867  return "could not measure benchmark, maybe it was optimized away";
6868  }
6869  };
6870 
6871  template <typename Clock, typename Fun>
6872  TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6873  auto iters = seed;
6874  while (iters < (1 << 30)) {
6875  auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6876 
6877  if (Timing.elapsed >= how_long) {
6878  return { Timing.elapsed, std::move(Timing.result), iters };
6879  }
6880  iters *= 2;
6881  }
6882  throw optimized_away_error{};
6883  }
6884  } // namespace Detail
6885  } // namespace Benchmark
6886 } // namespace Catch
6887 
6888 // end catch_run_for_at_least.hpp
6889 #include <algorithm>
6890 
6891 namespace Catch {
6892  namespace Benchmark {
6893  template <typename Duration>
6894  struct ExecutionPlan {
6895  int iterations_per_sample;
6896  Duration estimated_duration;
6897  Detail::BenchmarkFunction benchmark;
6898  Duration warmup_time;
6899  int warmup_iterations;
6900 
6901  template <typename Duration2>
6902  operator ExecutionPlan<Duration2>() const {
6903  return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6904  }
6905 
6906  template <typename Clock>
6907  std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6908  // warmup a bit
6909  Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6910 
6911  std::vector<FloatDuration<Clock>> times;
6912  times.reserve(cfg.benchmarkSamples());
6913  std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6914  Detail::ChronometerModel<Clock> model;
6915  this->benchmark(Chronometer(model, iterations_per_sample));
6916  auto sample_time = model.elapsed() - env.clock_cost.mean;
6917  if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6918  return sample_time / iterations_per_sample;
6919  });
6920  return times;
6921  }
6922  };
6923  } // namespace Benchmark
6924 } // namespace Catch
6925 
6926 // end catch_execution_plan.hpp
6927 // start catch_estimate_clock.hpp
6928 
6929  // Environment measurement
6930 
6931 
6932 // start catch_stats.hpp
6933 
6934 // Statistical analysis tools
6935 
6936 
6937 #include <algorithm>
6938 #include <functional>
6939 #include <vector>
6940 #include <iterator>
6941 #include <numeric>
6942 #include <tuple>
6943 #include <cmath>
6944 #include <utility>
6945 #include <cstddef>
6946 #include <random>
6947 
6948 namespace Catch {
6949  namespace Benchmark {
6950  namespace Detail {
6951  using sample = std::vector<double>;
6952 
6953  double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6954 
6955  template <typename Iterator>
6956  OutlierClassification classify_outliers(Iterator first, Iterator last) {
6957  std::vector<double> copy(first, last);
6958 
6959  auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6960  auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6961  auto iqr = q3 - q1;
6962  auto los = q1 - (iqr * 3.);
6963  auto lom = q1 - (iqr * 1.5);
6964  auto him = q3 + (iqr * 1.5);
6965  auto his = q3 + (iqr * 3.);
6966 
6967  OutlierClassification o;
6968  for (; first != last; ++first) {
6969  auto&& t = *first;
6970  if (t < los) ++o.low_severe;
6971  else if (t < lom) ++o.low_mild;
6972  else if (t > his) ++o.high_severe;
6973  else if (t > him) ++o.high_mild;
6974  ++o.samples_seen;
6975  }
6976  return o;
6977  }
6978 
6979  template <typename Iterator>
6980  double mean(Iterator first, Iterator last) {
6981  auto count = last - first;
6982  double sum = std::accumulate(first, last, 0.);
6983  return sum / count;
6984  }
6985 
6986  template <typename URng, typename Iterator, typename Estimator>
6987  sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
6988  auto n = last - first;
6989  std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
6990 
6991  sample out;
6992  out.reserve(resamples);
6993  std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
6994  std::vector<double> resampled;
6995  resampled.reserve(n);
6996  std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
6997  return estimator(resampled.begin(), resampled.end());
6998  });
6999  std::sort(out.begin(), out.end());
7000  return out;
7001  }
7002 
7003  template <typename Estimator, typename Iterator>
7004  sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7005  auto n = last - first;
7006  auto second = std::next(first);
7007  sample results;
7008  results.reserve(n);
7009 
7010  for (auto it = first; it != last; ++it) {
7011  std::iter_swap(it, first);
7012  results.push_back(estimator(second, last));
7013  }
7014 
7015  return results;
7016  }
7017 
7018  inline double normal_cdf(double x) {
7019  return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7020  }
7021 
7022  double erfc_inv(double x);
7023 
7024  double normal_quantile(double p);
7025 
7026  template <typename Iterator, typename Estimator>
7027  Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
7028  auto n_samples = last - first;
7029 
7030  double point = estimator(first, last);
7031  // Degenerate case with a single sample
7032  if (n_samples == 1) return { point, point, point, confidence_level };
7033 
7034  sample jack = jackknife(estimator, first, last);
7035  double jack_mean = mean(jack.begin(), jack.end());
7036  double sum_squares, sum_cubes;
7037  std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
7038  auto d = jack_mean - x;
7039  auto d2 = d * d;
7040  auto d3 = d2 * d;
7041  return { sqcb.first + d2, sqcb.second + d3 };
7042  });
7043 
7044  double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7045  int n = static_cast<int>(resample.size());
7046  double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
7047  // degenerate case with uniform samples
7048  if (prob_n == 0) return { point, point, point, confidence_level };
7049 
7050  double bias = normal_quantile(prob_n);
7051  double z1 = normal_quantile((1. - confidence_level) / 2.);
7052 
7053  auto cumn = [n](double x) -> int {
7054  return std::lround(normal_cdf(x) * n); };
7055  auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7056  double b1 = bias + z1;
7057  double b2 = bias - z1;
7058  double a1 = a(b1);
7059  double a2 = a(b2);
7060  auto lo = (std::max)(cumn(a1), 0);
7061  auto hi = (std::min)(cumn(a2), n - 1);
7062 
7063  return { point, resample[lo], resample[hi], confidence_level };
7064  }
7065 
7066  double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7067 
7068  struct bootstrap_analysis {
7069  Estimate<double> mean;
7070  Estimate<double> standard_deviation;
7071  double outlier_variance;
7072  };
7073 
7074  bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7075  } // namespace Detail
7076  } // namespace Benchmark
7077 } // namespace Catch
7078 
7079 // end catch_stats.hpp
7080 #include <algorithm>
7081 #include <iterator>
7082 #include <tuple>
7083 #include <vector>
7084 #include <cmath>
7085 
7086 namespace Catch {
7087  namespace Benchmark {
7088  namespace Detail {
7089  template <typename Clock>
7090  std::vector<double> resolution(int k) {
7091  std::vector<TimePoint<Clock>> times;
7092  times.reserve(k + 1);
7093  std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7094 
7095  std::vector<double> deltas;
7096  deltas.reserve(k);
7097  std::transform(std::next(times.begin()), times.end(), times.begin(),
7098  std::back_inserter(deltas),
7099  [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7100 
7101  return deltas;
7102  }
7103 
7104  const auto warmup_iterations = 10000;
7105  const auto warmup_time = std::chrono::milliseconds(100);
7106  const auto minimum_ticks = 1000;
7107  const auto warmup_seed = 10000;
7108  const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7109  const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7110  const auto clock_cost_estimation_tick_limit = 100000;
7111  const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7112  const auto clock_cost_estimation_iterations = 10000;
7113 
7114  template <typename Clock>
7115  int warmup() {
7116  return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7117  .iterations;
7118  }
7119  template <typename Clock>
7120  EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7121  auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7122  .result;
7123  return {
7124  FloatDuration<Clock>(mean(r.begin(), r.end())),
7125  classify_outliers(r.begin(), r.end()),
7126  };
7127  }
7128  template <typename Clock>
7129  EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7130  auto time_limit = (std::min)(
7131  resolution * clock_cost_estimation_tick_limit,
7132  FloatDuration<Clock>(clock_cost_estimation_time_limit));
7133  auto time_clock = [](int k) {
7134  return Detail::measure<Clock>([k] {
7135  for (int i = 0; i < k; ++i) {
7136  volatile auto ignored = Clock::now();
7137  (void)ignored;
7138  }
7139  }).elapsed;
7140  };
7141  time_clock(1);
7142  int iters = clock_cost_estimation_iterations;
7143  auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7144  std::vector<double> times;
7145  int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7146  times.reserve(nsamples);
7147  std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7148  return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7149  });
7150  return {
7151  FloatDuration<Clock>(mean(times.begin(), times.end())),
7152  classify_outliers(times.begin(), times.end()),
7153  };
7154  }
7155 
7156  template <typename Clock>
7157  Environment<FloatDuration<Clock>> measure_environment() {
7158  static Environment<FloatDuration<Clock>>* env = nullptr;
7159  if (env) {
7160  return *env;
7161  }
7162 
7163  auto iters = Detail::warmup<Clock>();
7164  auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7165  auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7166 
7167  env = new Environment<FloatDuration<Clock>>{ resolution, cost };
7168  return *env;
7169  }
7170  } // namespace Detail
7171  } // namespace Benchmark
7172 } // namespace Catch
7173 
7174 // end catch_estimate_clock.hpp
7175 // start catch_analyse.hpp
7176 
7177  // Run and analyse one benchmark
7178 
7179 
7180 // start catch_sample_analysis.hpp
7181 
7182 // Benchmark results
7183 
7184 
7185 #include <algorithm>
7186 #include <vector>
7187 #include <string>
7188 #include <iterator>
7189 
7190 namespace Catch {
7191  namespace Benchmark {
7192  template <typename Duration>
7193  struct SampleAnalysis {
7194  std::vector<Duration> samples;
7195  Estimate<Duration> mean;
7196  Estimate<Duration> standard_deviation;
7197  OutlierClassification outliers;
7198  double outlier_variance;
7199 
7200  template <typename Duration2>
7201  operator SampleAnalysis<Duration2>() const {
7202  std::vector<Duration2> samples2;
7203  samples2.reserve(samples.size());
7204  std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7205  return {
7206  std::move(samples2),
7207  mean,
7208  standard_deviation,
7209  outliers,
7210  outlier_variance,
7211  };
7212  }
7213  };
7214  } // namespace Benchmark
7215 } // namespace Catch
7216 
7217 // end catch_sample_analysis.hpp
7218 #include <algorithm>
7219 #include <iterator>
7220 #include <vector>
7221 
7222 namespace Catch {
7223  namespace Benchmark {
7224  namespace Detail {
7225  template <typename Duration, typename Iterator>
7226  SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7227  if (!cfg.benchmarkNoAnalysis()) {
7228  std::vector<double> samples;
7229  samples.reserve(last - first);
7230  std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7231 
7232  auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7233  auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7234 
7235  auto wrap_estimate = [](Estimate<double> e) {
7236  return Estimate<Duration> {
7237  Duration(e.point),
7238  Duration(e.lower_bound),
7239  Duration(e.upper_bound),
7240  e.confidence_interval,
7241  };
7242  };
7243  std::vector<Duration> samples2;
7244  samples2.reserve(samples.size());
7245  std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7246  return {
7247  std::move(samples2),
7248  wrap_estimate(analysis.mean),
7249  wrap_estimate(analysis.standard_deviation),
7250  outliers,
7251  analysis.outlier_variance,
7252  };
7253  } else {
7254  std::vector<Duration> samples;
7255  samples.reserve(last - first);
7256 
7257  Duration mean = Duration(0);
7258  int i = 0;
7259  for (auto it = first; it < last; ++it, ++i) {
7260  samples.push_back(Duration(*it));
7261  mean += Duration(*it);
7262  }
7263  mean /= i;
7264 
7265  return {
7266  std::move(samples),
7267  Estimate<Duration>{mean, mean, mean, 0.0},
7268  Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7269  OutlierClassification{},
7270  0.0
7271  };
7272  }
7273  }
7274  } // namespace Detail
7275  } // namespace Benchmark
7276 } // namespace Catch
7277 
7278 // end catch_analyse.hpp
7279 #include <algorithm>
7280 #include <functional>
7281 #include <string>
7282 #include <vector>
7283 #include <cmath>
7284 
7285 namespace Catch {
7286  namespace Benchmark {
7287  struct Benchmark {
7288  Benchmark(std::string &&name)
7289  : name(std::move(name)) {}
7290 
7291  template <class FUN>
7292  Benchmark(std::string &&name, FUN &&func)
7293  : fun(std::move(func)), name(std::move(name)) {}
7294 
7295  template <typename Clock>
7296  ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7297  auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7298  auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7299  auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7300  int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7301  return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7302  }
7303 
7304  template <typename Clock = default_clock>
7305  void run() {
7306  IConfigPtr cfg = getCurrentContext().getConfig();
7307 
7308  auto env = Detail::measure_environment<Clock>();
7309 
7310  getResultCapture().benchmarkPreparing(name);
7311  CATCH_TRY{
7312  auto plan = user_code([&] {
7313  return prepare<Clock>(*cfg, env);
7314  });
7315 
7316  BenchmarkInfo info {
7317  name,
7318  plan.estimated_duration.count(),
7319  plan.iterations_per_sample,
7320  cfg->benchmarkSamples(),
7321  cfg->benchmarkResamples(),
7322  env.clock_resolution.mean.count(),
7323  env.clock_cost.mean.count()
7324  };
7325 
7326  getResultCapture().benchmarkStarting(info);
7327 
7328  auto samples = user_code([&] {
7329  return plan.template run<Clock>(*cfg, env);
7330  });
7331 
7332  auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7333  BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7334  getResultCapture().benchmarkEnded(stats);
7335 
7336  } CATCH_CATCH_ALL{
7337  if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7338  std::rethrow_exception(std::current_exception());
7339  }
7340  }
7341 
7342  // sets lambda to be used in fun *and* executes benchmark!
7343  template <typename Fun,
7344  typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7345  Benchmark & operator=(Fun func) {
7346  fun = Detail::BenchmarkFunction(func);
7347  run();
7348  return *this;
7349  }
7350 
7351  explicit operator bool() {
7352  return true;
7353  }
7354 
7355  private:
7356  Detail::BenchmarkFunction fun;
7357  std::string name;
7358  };
7359  }
7360 } // namespace Catch
7361 
7362 #define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7363 #define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7364 
7365 #define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7366  if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7367  BenchmarkName = [&](int benchmarkIndex)
7368 
7369 #define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7370  if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7371  BenchmarkName = [&]
7372 
7373 // end catch_benchmark.hpp
7374 // start catch_constructor.hpp
7375 
7376 // Constructor and destructor helpers
7377 
7378 
7379 #include <type_traits>
7380 
7381 namespace Catch {
7382  namespace Benchmark {
7383  namespace Detail {
7384  template <typename T, bool Destruct>
7385  struct ObjectStorage
7386  {
7387  using TStorage = typename std::aligned_storage<sizeof(T), std::alignment_of<T>::value>::type;
7388 
7389  ObjectStorage() : data() {}
7390 
7391  ObjectStorage(const ObjectStorage& other)
7392  {
7393  new(&data) T(other.stored_object());
7394  }
7395 
7396  ObjectStorage(ObjectStorage&& other)
7397  {
7398  new(&data) T(std::move(other.stored_object()));
7399  }
7400 
7401  ~ObjectStorage() { destruct_on_exit<T>(); }
7402 
7403  template <typename... Args>
7404  void construct(Args&&... args)
7405  {
7406  new (&data) T(std::forward<Args>(args)...);
7407  }
7408 
7409  template <bool AllowManualDestruction = !Destruct>
7410  typename std::enable_if<AllowManualDestruction>::type destruct()
7411  {
7412  stored_object().~T();
7413  }
7414 
7415  private:
7416  // If this is a constructor benchmark, destruct the underlying object
7417  template <typename U>
7418  void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7419  // Otherwise, don't
7420  template <typename U>
7421  void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
7422 
7423  T& stored_object() {
7424  return *static_cast<T*>(static_cast<void*>(&data));
7425  }
7426 
7427  T const& stored_object() const {
7428  return *static_cast<T*>(static_cast<void*>(&data));
7429  }
7430 
7431  TStorage data;
7432  };
7433  }
7434 
7435  template <typename T>
7436  using storage_for = Detail::ObjectStorage<T, true>;
7437 
7438  template <typename T>
7439  using destructable_object = Detail::ObjectStorage<T, false>;
7440  }
7441 }
7442 
7443 // end catch_constructor.hpp
7444 // end catch_benchmarking_all.hpp
7445 #endif
7446 
7447 #endif // ! CATCH_CONFIG_IMPL_ONLY
7448 
7449 #ifdef CATCH_IMPL
7450 // start catch_impl.hpp
7451 
7452 #ifdef __clang__
7453 #pragma clang diagnostic push
7454 #pragma clang diagnostic ignored "-Wweak-vtables"
7455 #endif
7456 
7457 // Keep these here for external reporters
7458 // start catch_test_case_tracker.h
7459 
7460 #include <string>
7461 #include <vector>
7462 #include <memory>
7463 
7464 namespace Catch {
7465 namespace TestCaseTracking {
7466 
7467  struct NameAndLocation {
7468  std::string name;
7469  SourceLineInfo location;
7470 
7471  NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
7472  friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7473  return lhs.name == rhs.name
7474  && lhs.location == rhs.location;
7475  }
7476  };
7477 
7478  class ITracker;
7479 
7480  using ITrackerPtr = std::shared_ptr<ITracker>;
7481 
7482  class ITracker {
7483  NameAndLocation m_nameAndLocation;
7484 
7485  public:
7486  ITracker(NameAndLocation const& nameAndLoc) :
7487  m_nameAndLocation(nameAndLoc)
7488  {}
7489 
7490  // static queries
7491  NameAndLocation const& nameAndLocation() const {
7492  return m_nameAndLocation;
7493  }
7494 
7495  virtual ~ITracker();
7496 
7497  // dynamic queries
7498  virtual bool isComplete() const = 0; // Successfully completed or failed
7499  virtual bool isSuccessfullyCompleted() const = 0;
7500  virtual bool isOpen() const = 0; // Started but not complete
7501  virtual bool hasChildren() const = 0;
7502  virtual bool hasStarted() const = 0;
7503 
7504  virtual ITracker& parent() = 0;
7505 
7506  // actions
7507  virtual void close() = 0; // Successfully complete
7508  virtual void fail() = 0;
7509  virtual void markAsNeedingAnotherRun() = 0;
7510 
7511  virtual void addChild( ITrackerPtr const& child ) = 0;
7512  virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7513  virtual void openChild() = 0;
7514 
7515  // Debug/ checking
7516  virtual bool isSectionTracker() const = 0;
7517  virtual bool isGeneratorTracker() const = 0;
7518  };
7519 
7520  class TrackerContext {
7521 
7522  enum RunState {
7523  NotStarted,
7524  Executing,
7525  CompletedCycle
7526  };
7527 
7528  ITrackerPtr m_rootTracker;
7529  ITracker* m_currentTracker = nullptr;
7530  RunState m_runState = NotStarted;
7531 
7532  public:
7533 
7534  ITracker& startRun();
7535  void endRun();
7536 
7537  void startCycle();
7538  void completeCycle();
7539 
7540  bool completedCycle() const;
7541  ITracker& currentTracker();
7542  void setCurrentTracker( ITracker* tracker );
7543  };
7544 
7545  class TrackerBase : public ITracker {
7546  protected:
7547  enum CycleState {
7548  NotStarted,
7549  Executing,
7550  ExecutingChildren,
7551  NeedsAnotherRun,
7552  CompletedSuccessfully,
7553  Failed
7554  };
7555 
7556  using Children = std::vector<ITrackerPtr>;
7557  TrackerContext& m_ctx;
7558  ITracker* m_parent;
7559  Children m_children;
7560  CycleState m_runState = NotStarted;
7561 
7562  public:
7563  TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7564 
7565  bool isComplete() const override;
7566  bool isSuccessfullyCompleted() const override;
7567  bool isOpen() const override;
7568  bool hasChildren() const override;
7569  bool hasStarted() const override {
7570  return m_runState != NotStarted;
7571  }
7572 
7573  void addChild( ITrackerPtr const& child ) override;
7574 
7575  ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7576  ITracker& parent() override;
7577 
7578  void openChild() override;
7579 
7580  bool isSectionTracker() const override;
7581  bool isGeneratorTracker() const override;
7582 
7583  void open();
7584 
7585  void close() override;
7586  void fail() override;
7587  void markAsNeedingAnotherRun() override;
7588 
7589  private:
7590  void moveToParent();
7591  void moveToThis();
7592  };
7593 
7594  class SectionTracker : public TrackerBase {
7595  std::vector<std::string> m_filters;
7596  std::string m_trimmed_name;
7597  public:
7598  SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7599 
7600  bool isSectionTracker() const override;
7601 
7602  bool isComplete() const override;
7603 
7604  static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7605 
7606  void tryOpen();
7607 
7608  void addInitialFilters( std::vector<std::string> const& filters );
7609  void addNextFilters( std::vector<std::string> const& filters );
7611  std::vector<std::string> const& getFilters() const;
7613  std::string const& trimmedName() const;
7614  };
7615 
7616 } // namespace TestCaseTracking
7617 
7618 using TestCaseTracking::ITracker;
7619 using TestCaseTracking::TrackerContext;
7620 using TestCaseTracking::SectionTracker;
7621 
7622 } // namespace Catch
7623 
7624 // end catch_test_case_tracker.h
7625 
7626 // start catch_leak_detector.h
7627 
7628 namespace Catch {
7629 
7630  struct LeakDetector {
7631  LeakDetector();
7632  ~LeakDetector();
7633  };
7634 
7635 }
7636 // end catch_leak_detector.h
7637 // Cpp files will be included in the single-header file here
7638 // start catch_stats.cpp
7639 
7640 // Statistical analysis tools
7641 
7642 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7643 
7644 #include <cassert>
7645 #include <random>
7646 
7647 #if defined(CATCH_CONFIG_USE_ASYNC)
7648 #include <future>
7649 #endif
7650 
7651 namespace {
7652  double erf_inv(double x) {
7653  // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7654  double w, p;
7655 
7656  w = -log((1.0 - x) * (1.0 + x));
7657 
7658  if (w < 6.250000) {
7659  w = w - 3.125000;
7660  p = -3.6444120640178196996e-21;
7661  p = -1.685059138182016589e-19 + p * w;
7662  p = 1.2858480715256400167e-18 + p * w;
7663  p = 1.115787767802518096e-17 + p * w;
7664  p = -1.333171662854620906e-16 + p * w;
7665  p = 2.0972767875968561637e-17 + p * w;
7666  p = 6.6376381343583238325e-15 + p * w;
7667  p = -4.0545662729752068639e-14 + p * w;
7668  p = -8.1519341976054721522e-14 + p * w;
7669  p = 2.6335093153082322977e-12 + p * w;
7670  p = -1.2975133253453532498e-11 + p * w;
7671  p = -5.4154120542946279317e-11 + p * w;
7672  p = 1.051212273321532285e-09 + p * w;
7673  p = -4.1126339803469836976e-09 + p * w;
7674  p = -2.9070369957882005086e-08 + p * w;
7675  p = 4.2347877827932403518e-07 + p * w;
7676  p = -1.3654692000834678645e-06 + p * w;
7677  p = -1.3882523362786468719e-05 + p * w;
7678  p = 0.0001867342080340571352 + p * w;
7679  p = -0.00074070253416626697512 + p * w;
7680  p = -0.0060336708714301490533 + p * w;
7681  p = 0.24015818242558961693 + p * w;
7682  p = 1.6536545626831027356 + p * w;
7683  } else if (w < 16.000000) {
7684  w = sqrt(w) - 3.250000;
7685  p = 2.2137376921775787049e-09;
7686  p = 9.0756561938885390979e-08 + p * w;
7687  p = -2.7517406297064545428e-07 + p * w;
7688  p = 1.8239629214389227755e-08 + p * w;
7689  p = 1.5027403968909827627e-06 + p * w;
7690  p = -4.013867526981545969e-06 + p * w;
7691  p = 2.9234449089955446044e-06 + p * w;
7692  p = 1.2475304481671778723e-05 + p * w;
7693  p = -4.7318229009055733981e-05 + p * w;
7694  p = 6.8284851459573175448e-05 + p * w;
7695  p = 2.4031110387097893999e-05 + p * w;
7696  p = -0.0003550375203628474796 + p * w;
7697  p = 0.00095328937973738049703 + p * w;
7698  p = -0.0016882755560235047313 + p * w;
7699  p = 0.0024914420961078508066 + p * w;
7700  p = -0.0037512085075692412107 + p * w;
7701  p = 0.005370914553590063617 + p * w;
7702  p = 1.0052589676941592334 + p * w;
7703  p = 3.0838856104922207635 + p * w;
7704  } else {
7705  w = sqrt(w) - 5.000000;
7706  p = -2.7109920616438573243e-11;
7707  p = -2.5556418169965252055e-10 + p * w;
7708  p = 1.5076572693500548083e-09 + p * w;
7709  p = -3.7894654401267369937e-09 + p * w;
7710  p = 7.6157012080783393804e-09 + p * w;
7711  p = -1.4960026627149240478e-08 + p * w;
7712  p = 2.9147953450901080826e-08 + p * w;
7713  p = -6.7711997758452339498e-08 + p * w;
7714  p = 2.2900482228026654717e-07 + p * w;
7715  p = -9.9298272942317002539e-07 + p * w;
7716  p = 4.5260625972231537039e-06 + p * w;
7717  p = -1.9681778105531670567e-05 + p * w;
7718  p = 7.5995277030017761139e-05 + p * w;
7719  p = -0.00021503011930044477347 + p * w;
7720  p = -0.00013871931833623122026 + p * w;
7721  p = 1.0103004648645343977 + p * w;
7722  p = 4.8499064014085844221 + p * w;
7723  }
7724  return p * x;
7725  }
7726 
7727  double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7728  auto m = Catch::Benchmark::Detail::mean(first, last);
7729  double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7730  double diff = b - m;
7731  return a + diff * diff;
7732  }) / (last - first);
7733  return std::sqrt(variance);
7734  }
7735 
7736 }
7737 
7738 namespace Catch {
7739  namespace Benchmark {
7740  namespace Detail {
7741 
7742  double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7743  auto count = last - first;
7744  double idx = (count - 1) * k / static_cast<double>(q);
7745  int j = static_cast<int>(idx);
7746  double g = idx - j;
7747  std::nth_element(first, first + j, last);
7748  auto xj = first[j];
7749  if (g == 0) return xj;
7750 
7751  auto xj1 = *std::min_element(first + (j + 1), last);
7752  return xj + g * (xj1 - xj);
7753  }
7754 
7755  double erfc_inv(double x) {
7756  return erf_inv(1.0 - x);
7757  }
7758 
7759  double normal_quantile(double p) {
7760  static const double ROOT_TWO = std::sqrt(2.0);
7761 
7762  double result = 0.0;
7763  assert(p >= 0 && p <= 1);
7764  if (p < 0 || p > 1) {
7765  return result;
7766  }
7767 
7768  result = -erfc_inv(2.0 * p);
7769  // result *= normal distribution standard deviation (1.0) * sqrt(2)
7770  result *= /*sd * */ ROOT_TWO;
7771  // result += normal disttribution mean (0)
7772  return result;
7773  }
7774 
7775  double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7776  double sb = stddev.point;
7777  double mn = mean.point / n;
7778  double mg_min = mn / 2.;
7779  double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7780  double sg2 = sg * sg;
7781  double sb2 = sb * sb;
7782 
7783  auto c_max = [n, mn, sb2, sg2](double x) -> double {
7784  double k = mn - x;
7785  double d = k * k;
7786  double nd = n * d;
7787  double k0 = -n * nd;
7788  double k1 = sb2 - n * sg2 + nd;
7789  double det = k1 * k1 - 4 * sg2 * k0;
7790  return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7791  };
7792 
7793  auto var_out = [n, sb2, sg2](double c) {
7794  double nc = n - c;
7795  return (nc / n) * (sb2 - nc * sg2);
7796  };
7797 
7798  return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7799  }
7800 
7801  bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7802  CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7803  CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7804  static std::random_device entropy;
7805  CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7806 
7807  auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7808 
7809  auto mean = &Detail::mean<std::vector<double>::iterator>;
7810  auto stddev = &standard_deviation;
7811 
7812 #if defined(CATCH_CONFIG_USE_ASYNC)
7813  auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7814  auto seed = entropy();
7815  return std::async(std::launch::async, [=] {
7816  std::mt19937 rng(seed);
7817  auto resampled = resample(rng, n_resamples, first, last, f);
7818  return bootstrap(confidence_level, first, last, resampled, f);
7819  });
7820  };
7821 
7822  auto mean_future = Estimate(mean);
7823  auto stddev_future = Estimate(stddev);
7824 
7825  auto mean_estimate = mean_future.get();
7826  auto stddev_estimate = stddev_future.get();
7827 #else
7828  auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7829  auto seed = entropy();
7830  std::mt19937 rng(seed);
7831  auto resampled = resample(rng, n_resamples, first, last, f);
7832  return bootstrap(confidence_level, first, last, resampled, f);
7833  };
7834 
7835  auto mean_estimate = Estimate(mean);
7836  auto stddev_estimate = Estimate(stddev);
7837 #endif // CATCH_USE_ASYNC
7838 
7839  double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7840 
7841  return { mean_estimate, stddev_estimate, outlier_variance };
7842  }
7843  } // namespace Detail
7844  } // namespace Benchmark
7845 } // namespace Catch
7846 
7847 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7848 // end catch_stats.cpp
7849 // start catch_approx.cpp
7850 
7851 #include <cmath>
7852 #include <limits>
7853 
7854 namespace {
7855 
7856 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
7857 // But without the subtraction to allow for INFINITY in comparison
7858 bool marginComparison(double lhs, double rhs, double margin) {
7859  return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7860 }
7861 
7862 }
7863 
7864 namespace Catch {
7865 namespace Detail {
7866 
7867  Approx::Approx ( double value )
7868  : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7869  m_margin( 0.0 ),
7870  m_scale( 0.0 ),
7871  m_value( value )
7872  {}
7873 
7874  Approx Approx::custom() {
7875  return Approx( 0 );
7876  }
7877 
7878  Approx Approx::operator-() const {
7879  auto temp(*this);
7880  temp.m_value = -temp.m_value;
7881  return temp;
7882  }
7883 
7884  std::string Approx::toString() const {
7886  rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7887  return rss.str();
7888  }
7889 
7890  bool Approx::equalityComparisonImpl(const double other) const {
7891  // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7892  // Thanks to Richard Harris for his help refining the scaled margin value
7893  return marginComparison(m_value, other, m_margin)
7894  || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7895  }
7896 
7897  void Approx::setMargin(double newMargin) {
7898  CATCH_ENFORCE(newMargin >= 0,
7899  "Invalid Approx::margin: " << newMargin << '.'
7900  << " Approx::Margin has to be non-negative.");
7901  m_margin = newMargin;
7902  }
7903 
7904  void Approx::setEpsilon(double newEpsilon) {
7905  CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7906  "Invalid Approx::epsilon: " << newEpsilon << '.'
7907  << " Approx::epsilon has to be in [0, 1]");
7908  m_epsilon = newEpsilon;
7909  }
7910 
7911 } // end namespace Detail
7912 
7913 namespace literals {
7914  Detail::Approx operator "" _a(long double val) {
7915  return Detail::Approx(val);
7916  }
7917  Detail::Approx operator "" _a(unsigned long long val) {
7918  return Detail::Approx(val);
7919  }
7920 } // end namespace literals
7921 
7923  return value.toString();
7924 }
7925 
7926 } // end namespace Catch
7927 // end catch_approx.cpp
7928 // start catch_assertionhandler.cpp
7929 
7930 // start catch_debugger.h
7931 
7932 namespace Catch {
7933  bool isDebuggerActive();
7934 }
7935 
7936 #ifdef CATCH_PLATFORM_MAC
7937 
7938  #if defined(__i386__) || defined(__x86_64__)
7939  #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7940  #elif defined(__aarch64__)
7941  #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7942  #endif
7943 
7944 #elif defined(CATCH_PLATFORM_IPHONE)
7945 
7946  // use inline assembler
7947  #if defined(__i386__) || defined(__x86_64__)
7948  #define CATCH_TRAP() __asm__("int $3")
7949  #elif defined(__aarch64__)
7950  #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7951  #elif defined(__arm__) && !defined(__thumb__)
7952  #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7953  #elif defined(__arm__) && defined(__thumb__)
7954  #define CATCH_TRAP() __asm__(".inst 0xde01")
7955  #endif
7956 
7957 #elif defined(CATCH_PLATFORM_LINUX)
7958  // If we can use inline assembler, do it because this allows us to break
7959  // directly at the location of the failing check instead of breaking inside
7960  // raise() called from it, i.e. one stack frame below.
7961  #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7962  #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7963  #else // Fall back to the generic way.
7964  #include <signal.h>
7965 
7966  #define CATCH_TRAP() raise(SIGTRAP)
7967  #endif
7968 #elif defined(_MSC_VER)
7969  #define CATCH_TRAP() __debugbreak()
7970 #elif defined(__MINGW32__)
7971  extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7972  #define CATCH_TRAP() DebugBreak()
7973 #endif
7974 
7975 #ifndef CATCH_BREAK_INTO_DEBUGGER
7976  #ifdef CATCH_TRAP
7977  #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7978  #else
7979  #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7980  #endif
7981 #endif
7982 
7983 // end catch_debugger.h
7984 // start catch_run_context.h
7985 
7986 // start catch_fatal_condition.h
7987 
7988 #include <cassert>
7989 
7990 namespace Catch {
7991 
7992  // Wrapper for platform-specific fatal error (signals/SEH) handlers
7993  //
7994  // Tries to be cooperative with other handlers, and not step over
7995  // other handlers. This means that unknown structured exceptions
7996  // are passed on, previous signal handlers are called, and so on.
7997  //
7998  // Can only be instantiated once, and assumes that once a signal
7999  // is caught, the binary will end up terminating. Thus, there
8000  class FatalConditionHandler {
8001  bool m_started = false;
8002 
8003  // Install/disengage implementation for specific platform.
8004  // Should be if-defed to work on current platform, can assume
8005  // engage-disengage 1:1 pairing.
8006  void engage_platform();
8007  void disengage_platform();
8008  public:
8009  // Should also have platform-specific implementations as needed
8010  FatalConditionHandler();
8011  ~FatalConditionHandler();
8012 
8013  void engage() {
8014  assert(!m_started && "Handler cannot be installed twice.");
8015  m_started = true;
8016  engage_platform();
8017  }
8018 
8019  void disengage() {
8020  assert(m_started && "Handler cannot be uninstalled without being installed first");
8021  m_started = false;
8022  disengage_platform();
8023  }
8024  };
8025 
8027  class FatalConditionHandlerGuard {
8028  FatalConditionHandler* m_handler;
8029  public:
8030  FatalConditionHandlerGuard(FatalConditionHandler* handler):
8031  m_handler(handler) {
8032  m_handler->engage();
8033  }
8034  ~FatalConditionHandlerGuard() {
8035  m_handler->disengage();
8036  }
8037  };
8038 
8039 } // end namespace Catch
8040 
8041 // end catch_fatal_condition.h
8042 #include <string>
8043 
8044 namespace Catch {
8045 
8046  struct IMutableContext;
8047 
8049 
8050  class RunContext : public IResultCapture, public IRunner {
8051 
8052  public:
8053  RunContext( RunContext const& ) = delete;
8054  RunContext& operator =( RunContext const& ) = delete;
8055 
8056  explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8057 
8058  ~RunContext() override;
8059 
8060  void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8061  void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8062 
8063  Totals runTest(TestCase const& testCase);
8064 
8065  IConfigPtr config() const;
8066  IStreamingReporter& reporter() const;
8067 
8068  public: // IResultCapture
8069 
8070  // Assertion handlers
8071  void handleExpr
8072  ( AssertionInfo const& info,
8073  ITransientExpression const& expr,
8074  AssertionReaction& reaction ) override;
8075  void handleMessage
8076  ( AssertionInfo const& info,
8077  ResultWas::OfType resultType,
8078  StringRef const& message,
8079  AssertionReaction& reaction ) override;
8080  void handleUnexpectedExceptionNotThrown
8081  ( AssertionInfo const& info,
8082  AssertionReaction& reaction ) override;
8083  void handleUnexpectedInflightException
8084  ( AssertionInfo const& info,
8085  std::string const& message,
8086  AssertionReaction& reaction ) override;
8087  void handleIncomplete
8088  ( AssertionInfo const& info ) override;
8089  void handleNonExpr
8090  ( AssertionInfo const &info,
8091  ResultWas::OfType resultType,
8092  AssertionReaction &reaction ) override;
8093 
8094  bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
8095 
8096  void sectionEnded( SectionEndInfo const& endInfo ) override;
8097  void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
8098 
8099  auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
8100 
8101 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8102  void benchmarkPreparing( std::string const& name ) override;
8103  void benchmarkStarting( BenchmarkInfo const& info ) override;
8104  void benchmarkEnded( BenchmarkStats<> const& stats ) override;
8105  void benchmarkFailed( std::string const& error ) override;
8106 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8107 
8108  void pushScopedMessage( MessageInfo const& message ) override;
8109  void popScopedMessage( MessageInfo const& message ) override;
8110 
8111  void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
8112 
8113  std::string getCurrentTestName() const override;
8114 
8115  const AssertionResult* getLastResult() const override;
8116 
8117  void exceptionEarlyReported() override;
8118 
8119  void handleFatalErrorCondition( StringRef message ) override;
8120 
8121  bool lastAssertionPassed() override;
8122 
8123  void assertionPassed() override;
8124 
8125  public:
8126  // !TBD We need to do this another way!
8127  bool aborting() const final;
8128 
8129  private:
8130 
8131  void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8132  void invokeActiveTestCase();
8133 
8134  void resetAssertionInfo();
8135  bool testForMissingAssertions( Counts& assertions );
8136 
8137  void assertionEnded( AssertionResult const& result );
8138  void reportExpr
8139  ( AssertionInfo const &info,
8140  ResultWas::OfType resultType,
8141  ITransientExpression const *expr,
8142  bool negated );
8143 
8144  void populateReaction( AssertionReaction& reaction );
8145 
8146  private:
8147 
8148  void handleUnfinishedSections();
8149 
8150  TestRunInfo m_runInfo;
8151  IMutableContext& m_context;
8152  TestCase const* m_activeTestCase = nullptr;
8153  ITracker* m_testCaseTracker = nullptr;
8154  Option<AssertionResult> m_lastResult;
8155 
8156  IConfigPtr m_config;
8157  Totals m_totals;
8158  IStreamingReporterPtr m_reporter;
8159  std::vector<MessageInfo> m_messages;
8160  std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8161  AssertionInfo m_lastAssertionInfo;
8162  std::vector<SectionEndInfo> m_unfinishedSections;
8163  std::vector<ITracker*> m_activeSections;
8164  TrackerContext m_trackerContext;
8165  FatalConditionHandler m_fatalConditionhandler;
8166  bool m_lastAssertionPassed = false;
8167  bool m_shouldReportUnexpected = true;
8168  bool m_includeSuccessfulResults;
8169  };
8170 
8171  void seedRng(IConfig const& config);
8172  unsigned int rngSeed();
8173 } // end namespace Catch
8174 
8175 // end catch_run_context.h
8176 namespace Catch {
8177 
8178  namespace {
8179  auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
8180  expr.streamReconstructedExpression( os );
8181  return os;
8182  }
8183  }
8184 
8185  LazyExpression::LazyExpression( bool isNegated )
8186  : m_isNegated( isNegated )
8187  {}
8188 
8189  LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8190 
8191  LazyExpression::operator bool() const {
8192  return m_transientExpression != nullptr;
8193  }
8194 
8195  auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
8196  if( lazyExpr.m_isNegated )
8197  os << "!";
8198 
8199  if( lazyExpr ) {
8200  if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8201  os << "(" << *lazyExpr.m_transientExpression << ")";
8202  else
8203  os << *lazyExpr.m_transientExpression;
8204  }
8205  else {
8206  os << "{** error - unchecked empty expression requested **}";
8207  }
8208  return os;
8209  }
8210 
8211  AssertionHandler::AssertionHandler
8212  ( StringRef const& macroName,
8213  SourceLineInfo const& lineInfo,
8214  StringRef capturedExpression,
8215  ResultDisposition::Flags resultDisposition )
8216  : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8217  m_resultCapture( getResultCapture() )
8218  {}
8219 
8220  void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
8221  m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8222  }
8223  void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8224  m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8225  }
8226 
8227  auto AssertionHandler::allowThrows() const -> bool {
8228  return getCurrentContext().getConfig()->allowThrows();
8229  }
8230 
8231  void AssertionHandler::complete() {
8232  setCompleted();
8233  if( m_reaction.shouldDebugBreak ) {
8234 
8235  // If you find your debugger stopping you here then go one level up on the
8236  // call-stack for the code that caused it (typically a failed assertion)
8237 
8238  // (To go back to the test and change execution, jump over the throw, next)
8239  CATCH_BREAK_INTO_DEBUGGER();
8240  }
8241  if (m_reaction.shouldThrow) {
8242 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8244 #else
8245  CATCH_ERROR( "Test failure requires aborting test!" );
8246 #endif
8247  }
8248  }
8249  void AssertionHandler::setCompleted() {
8250  m_completed = true;
8251  }
8252 
8253  void AssertionHandler::handleUnexpectedInflightException() {
8254  m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8255  }
8256 
8257  void AssertionHandler::handleExceptionThrownAsExpected() {
8258  m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8259  }
8260  void AssertionHandler::handleExceptionNotThrownAsExpected() {
8261  m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8262  }
8263 
8264  void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8265  m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8266  }
8267 
8268  void AssertionHandler::handleThrowingCallSkipped() {
8269  m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8270  }
8271 
8272  // This is the overload that takes a string and infers the Equals matcher from it
8273  // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
8274  void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
8275  handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8276  }
8277 
8278 } // namespace Catch
8279 // end catch_assertionhandler.cpp
8280 // start catch_assertionresult.cpp
8281 
8282 namespace Catch {
8283  AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
8284  lazyExpression(_lazyExpression),
8285  resultType(_resultType) {}
8286 
8287  std::string AssertionResultData::reconstructExpression() const {
8288 
8289  if( reconstructedExpression.empty() ) {
8290  if( lazyExpression ) {
8292  rss << lazyExpression;
8293  reconstructedExpression = rss.str();
8294  }
8295  }
8296  return reconstructedExpression;
8297  }
8298 
8299  AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8300  : m_info( info ),
8301  m_resultData( data )
8302  {}
8303 
8304  // Result was a success
8305  bool AssertionResult::succeeded() const {
8306  return Catch::isOk( m_resultData.resultType );
8307  }
8308 
8309  // Result was a success, or failure is suppressed
8310  bool AssertionResult::isOk() const {
8311  return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8312  }
8313 
8314  ResultWas::OfType AssertionResult::getResultType() const {
8315  return m_resultData.resultType;
8316  }
8317 
8318  bool AssertionResult::hasExpression() const {
8319  return !m_info.capturedExpression.empty();
8320  }
8321 
8322  bool AssertionResult::hasMessage() const {
8323  return !m_resultData.message.empty();
8324  }
8325 
8326  std::string AssertionResult::getExpression() const {
8327  // Possibly overallocating by 3 characters should be basically free
8328  std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8329  if (isFalseTest(m_info.resultDisposition)) {
8330  expr += "!(";
8331  }
8332  expr += m_info.capturedExpression;
8333  if (isFalseTest(m_info.resultDisposition)) {
8334  expr += ')';
8335  }
8336  return expr;
8337  }
8338 
8339  std::string AssertionResult::getExpressionInMacro() const {
8340  std::string expr;
8341  if( m_info.macroName.empty() )
8342  expr = static_cast<std::string>(m_info.capturedExpression);
8343  else {
8344  expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8345  expr += m_info.macroName;
8346  expr += "( ";
8347  expr += m_info.capturedExpression;
8348  expr += " )";
8349  }
8350  return expr;
8351  }
8352 
8353  bool AssertionResult::hasExpandedExpression() const {
8354  return hasExpression() && getExpandedExpression() != getExpression();
8355  }
8356 
8357  std::string AssertionResult::getExpandedExpression() const {
8358  std::string expr = m_resultData.reconstructExpression();
8359  return expr.empty()
8360  ? getExpression()
8361  : expr;
8362  }
8363 
8364  std::string AssertionResult::getMessage() const {
8365  return m_resultData.message;
8366  }
8367  SourceLineInfo AssertionResult::getSourceInfo() const {
8368  return m_info.lineInfo;
8369  }
8370 
8371  StringRef AssertionResult::getTestMacroName() const {
8372  return m_info.macroName;
8373  }
8374 
8375 } // end namespace Catch
8376 // end catch_assertionresult.cpp
8377 // start catch_capture_matchers.cpp
8378 
8379 namespace Catch {
8380 
8382 
8383  // This is the general overload that takes a any string matcher
8384  // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8385  // the Equals matcher (so the header does not mention matchers)
8386  void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
8387  std::string exceptionMessage = Catch::translateActiveException();
8388  MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8389  handler.handleExpr( expr );
8390  }
8391 
8392 } // namespace Catch
8393 // end catch_capture_matchers.cpp
8394 // start catch_commandline.cpp
8395 
8396 // start catch_commandline.h
8397 
8398 // start catch_clara.h
8399 
8400 // Use Catch's value for console width (store Clara's off to the side, if present)
8401 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
8402 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8403 #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8404 #endif
8405 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8406 
8407 #ifdef __clang__
8408 #pragma clang diagnostic push
8409 #pragma clang diagnostic ignored "-Wweak-vtables"
8410 #pragma clang diagnostic ignored "-Wexit-time-destructors"
8411 #pragma clang diagnostic ignored "-Wshadow"
8412 #endif
8413 
8414 // start clara.hpp
8415 // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8416 //
8417 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8418 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8419 //
8420 // See https://github.com/philsquared/Clara for more details
8421 
8422 // Clara v1.1.5
8423 
8424 
8425 #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8426 #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8427 #endif
8428 
8429 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8430 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8431 #endif
8432 
8433 #ifndef CLARA_CONFIG_OPTIONAL_TYPE
8434 #ifdef __has_include
8435 #if __has_include(<optional>) && __cplusplus >= 201703L
8436 #include <optional>
8437 #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8438 #endif
8439 #endif
8440 #endif
8441 
8442 // ----------- #included from clara_textflow.hpp -----------
8443 
8444 // TextFlowCpp
8445 //
8446 // A single-header library for wrapping and laying out basic text, by Phil Nash
8447 //
8448 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8449 // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8450 //
8451 // This project is hosted at https://github.com/philsquared/textflowcpp
8452 
8453 
8454 #include <cassert>
8455 #include <ostream>
8456 #include <sstream>
8457 #include <vector>
8458 
8459 #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8460 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8461 #endif
8462 
8463 namespace Catch {
8464 namespace clara {
8465 namespace TextFlow {
8466 
8467 inline auto isWhitespace(char c) -> bool {
8468  static std::string chars = " \t\n\r";
8469  return chars.find(c) != std::string::npos;
8470 }
8471 inline auto isBreakableBefore(char c) -> bool {
8472  static std::string chars = "[({<|";
8473  return chars.find(c) != std::string::npos;
8474 }
8475 inline auto isBreakableAfter(char c) -> bool {
8476  static std::string chars = "])}>.,:;*+-=&/\\";
8477  return chars.find(c) != std::string::npos;
8478 }
8479 
8480 class Columns;
8481 
8482 class Column {
8483  std::vector<std::string> m_strings;
8484  size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8485  size_t m_indent = 0;
8486  size_t m_initialIndent = std::string::npos;
8487 
8488 public:
8489  class iterator {
8490  friend Column;
8491 
8492  Column const& m_column;
8493  size_t m_stringIndex = 0;
8494  size_t m_pos = 0;
8495 
8496  size_t m_len = 0;
8497  size_t m_end = 0;
8498  bool m_suffix = false;
8499 
8500  iterator(Column const& column, size_t stringIndex)
8501  : m_column(column),
8502  m_stringIndex(stringIndex) {}
8503 
8504  auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8505 
8506  auto isBoundary(size_t at) const -> bool {
8507  assert(at > 0);
8508  assert(at <= line().size());
8509 
8510  return at == line().size() ||
8511  (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8512  isBreakableBefore(line()[at]) ||
8513  isBreakableAfter(line()[at - 1]);
8514  }
8515 
8516  void calcLength() {
8517  assert(m_stringIndex < m_column.m_strings.size());
8518 
8519  m_suffix = false;
8520  auto width = m_column.m_width - indent();
8521  m_end = m_pos;
8522  if (line()[m_pos] == '\n') {
8523  ++m_end;
8524  }
8525  while (m_end < line().size() && line()[m_end] != '\n')
8526  ++m_end;
8527 
8528  if (m_end < m_pos + width) {
8529  m_len = m_end - m_pos;
8530  } else {
8531  size_t len = width;
8532  while (len > 0 && !isBoundary(m_pos + len))
8533  --len;
8534  while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8535  --len;
8536 
8537  if (len > 0) {
8538  m_len = len;
8539  } else {
8540  m_suffix = true;
8541  m_len = width - 1;
8542  }
8543  }
8544  }
8545 
8546  auto indent() const -> size_t {
8547  auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8548  return initial == std::string::npos ? m_column.m_indent : initial;
8549  }
8550 
8551  auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8552  return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8553  }
8554 
8555  public:
8556  using difference_type = std::ptrdiff_t;
8557  using value_type = std::string;
8558  using pointer = value_type * ;
8559  using reference = value_type & ;
8560  using iterator_category = std::forward_iterator_tag;
8561 
8562  explicit iterator(Column const& column) : m_column(column) {
8563  assert(m_column.m_width > m_column.m_indent);
8564  assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8565  calcLength();
8566  if (m_len == 0)
8567  m_stringIndex++; // Empty string
8568  }
8569 
8570  auto operator *() const -> std::string {
8571  assert(m_stringIndex < m_column.m_strings.size());
8572  assert(m_pos <= m_end);
8573  return addIndentAndSuffix(line().substr(m_pos, m_len));
8574  }
8575 
8576  auto operator ++() -> iterator& {
8577  m_pos += m_len;
8578  if (m_pos < line().size() && line()[m_pos] == '\n')
8579  m_pos += 1;
8580  else
8581  while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8582  ++m_pos;
8583 
8584  if (m_pos == line().size()) {
8585  m_pos = 0;
8586  ++m_stringIndex;
8587  }
8588  if (m_stringIndex < m_column.m_strings.size())
8589  calcLength();
8590  return *this;
8591  }
8592  auto operator ++(int) -> iterator {
8593  iterator prev(*this);
8594  operator++();
8595  return prev;
8596  }
8597 
8598  auto operator ==(iterator const& other) const -> bool {
8599  return
8600  m_pos == other.m_pos &&
8601  m_stringIndex == other.m_stringIndex &&
8602  &m_column == &other.m_column;
8603  }
8604  auto operator !=(iterator const& other) const -> bool {
8605  return !operator==(other);
8606  }
8607  };
8608  using const_iterator = iterator;
8609 
8610  explicit Column(std::string const& text) { m_strings.push_back(text); }
8611 
8612  auto width(size_t newWidth) -> Column& {
8613  assert(newWidth > 0);
8614  m_width = newWidth;
8615  return *this;
8616  }
8617  auto indent(size_t newIndent) -> Column& {
8618  m_indent = newIndent;
8619  return *this;
8620  }
8621  auto initialIndent(size_t newIndent) -> Column& {
8622  m_initialIndent = newIndent;
8623  return *this;
8624  }
8625 
8626  auto width() const -> size_t { return m_width; }
8627  auto begin() const -> iterator { return iterator(*this); }
8628  auto end() const -> iterator { return { *this, m_strings.size() }; }
8629 
8630  inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8631  bool first = true;
8632  for (auto line : col) {
8633  if (first)
8634  first = false;
8635  else
8636  os << "\n";
8637  os << line;
8638  }
8639  return os;
8640  }
8641 
8642  auto operator + (Column const& other)->Columns;
8643 
8644  auto toString() const -> std::string {
8645  std::ostringstream oss;
8646  oss << *this;
8647  return oss.str();
8648  }
8649 };
8650 
8651 class Spacer : public Column {
8652 
8653 public:
8654  explicit Spacer(size_t spaceWidth) : Column("") {
8655  width(spaceWidth);
8656  }
8657 };
8658 
8659 class Columns {
8660  std::vector<Column> m_columns;
8661 
8662 public:
8663 
8664  class iterator {
8665  friend Columns;
8666  struct EndTag {};
8667 
8668  std::vector<Column> const& m_columns;
8669  std::vector<Column::iterator> m_iterators;
8670  size_t m_activeIterators;
8671 
8672  iterator(Columns const& columns, EndTag)
8673  : m_columns(columns.m_columns),
8674  m_activeIterators(0) {
8675  m_iterators.reserve(m_columns.size());
8676 
8677  for (auto const& col : m_columns)
8678  m_iterators.push_back(col.end());
8679  }
8680 
8681  public:
8682  using difference_type = std::ptrdiff_t;
8683  using value_type = std::string;
8684  using pointer = value_type * ;
8685  using reference = value_type & ;
8686  using iterator_category = std::forward_iterator_tag;
8687 
8688  explicit iterator(Columns const& columns)
8689  : m_columns(columns.m_columns),
8690  m_activeIterators(m_columns.size()) {
8691  m_iterators.reserve(m_columns.size());
8692 
8693  for (auto const& col : m_columns)
8694  m_iterators.push_back(col.begin());
8695  }
8696 
8697  auto operator ==(iterator const& other) const -> bool {
8698  return m_iterators == other.m_iterators;
8699  }
8700  auto operator !=(iterator const& other) const -> bool {
8701  return m_iterators != other.m_iterators;
8702  }
8703  auto operator *() const -> std::string {
8704  std::string row, padding;
8705 
8706  for (size_t i = 0; i < m_columns.size(); ++i) {
8707  auto width = m_columns[i].width();
8708  if (m_iterators[i] != m_columns[i].end()) {
8709  std::string col = *m_iterators[i];
8710  row += padding + col;
8711  if (col.size() < width)
8712  padding = std::string(width - col.size(), ' ');
8713  else
8714  padding = "";
8715  } else {
8716  padding += std::string(width, ' ');
8717  }
8718  }
8719  return row;
8720  }
8721  auto operator ++() -> iterator& {
8722  for (size_t i = 0; i < m_columns.size(); ++i) {
8723  if (m_iterators[i] != m_columns[i].end())
8724  ++m_iterators[i];
8725  }
8726  return *this;
8727  }
8728  auto operator ++(int) -> iterator {
8729  iterator prev(*this);
8730  operator++();
8731  return prev;
8732  }
8733  };
8734  using const_iterator = iterator;
8735 
8736  auto begin() const -> iterator { return iterator(*this); }
8737  auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8738 
8739  auto operator += (Column const& col) -> Columns& {
8740  m_columns.push_back(col);
8741  return *this;
8742  }
8743  auto operator + (Column const& col) -> Columns {
8744  Columns combined = *this;
8745  combined += col;
8746  return combined;
8747  }
8748 
8749  inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8750 
8751  bool first = true;
8752  for (auto line : cols) {
8753  if (first)
8754  first = false;
8755  else
8756  os << "\n";
8757  os << line;
8758  }
8759  return os;
8760  }
8761 
8762  auto toString() const -> std::string {
8763  std::ostringstream oss;
8764  oss << *this;
8765  return oss.str();
8766  }
8767 };
8768 
8769 inline auto Column::operator + (Column const& other) -> Columns {
8770  Columns cols;
8771  cols += *this;
8772  cols += other;
8773  return cols;
8774 }
8775 }
8776 
8777 }
8778 }
8779 
8780 // ----------- end of #include from clara_textflow.hpp -----------
8781 // ........... back in clara.hpp
8782 
8783 #include <cctype>
8784 #include <string>
8785 #include <memory>
8786 #include <set>
8787 #include <algorithm>
8788 
8789 #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8790 #define CATCH_PLATFORM_WINDOWS
8791 #endif
8792 
8793 namespace Catch { namespace clara {
8794 namespace detail {
8795 
8796  // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8797  template<typename L>
8798  struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8799 
8800  template<typename ClassT, typename ReturnT, typename... Args>
8801  struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8802  static const bool isValid = false;
8803  };
8804 
8805  template<typename ClassT, typename ReturnT, typename ArgT>
8806  struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8807  static const bool isValid = true;
8808  using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8809  using ReturnType = ReturnT;
8810  };
8811 
8812  class TokenStream;
8813 
8814  // Transport for raw args (copied from main args, or supplied via init list for testing)
8815  class Args {
8816  friend TokenStream;
8817  std::string m_exeName;
8818  std::vector<std::string> m_args;
8819 
8820  public:
8821  Args( int argc, char const* const* argv )
8822  : m_exeName(argv[0]),
8823  m_args(argv + 1, argv + argc) {}
8824 
8825  Args( std::initializer_list<std::string> args )
8826  : m_exeName( *args.begin() ),
8827  m_args( args.begin()+1, args.end() )
8828  {}
8829 
8830  auto exeName() const -> std::string {
8831  return m_exeName;
8832  }
8833  };
8834 
8835  // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8836  // may encode an option + its argument if the : or = form is used
8837  enum class TokenType {
8838  Option, Argument
8839  };
8840  struct Token {
8841  TokenType type;
8842  std::string token;
8843  };
8844 
8845  inline auto isOptPrefix( char c ) -> bool {
8846  return c == '-'
8847 #ifdef CATCH_PLATFORM_WINDOWS
8848  || c == '/'
8849 #endif
8850  ;
8851  }
8852 
8853  // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8854  class TokenStream {
8855  using Iterator = std::vector<std::string>::const_iterator;
8856  Iterator it;
8857  Iterator itEnd;
8858  std::vector<Token> m_tokenBuffer;
8859 
8860  void loadBuffer() {
8861  m_tokenBuffer.resize( 0 );
8862 
8863  // Skip any empty strings
8864  while( it != itEnd && it->empty() )
8865  ++it;
8866 
8867  if( it != itEnd ) {
8868  auto const &next = *it;
8869  if( isOptPrefix( next[0] ) ) {
8870  auto delimiterPos = next.find_first_of( " :=" );
8871  if( delimiterPos != std::string::npos ) {
8872  m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8873  m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8874  } else {
8875  if( next[1] != '-' && next.size() > 2 ) {
8876  std::string opt = "- ";
8877  for( size_t i = 1; i < next.size(); ++i ) {
8878  opt[1] = next[i];
8879  m_tokenBuffer.push_back( { TokenType::Option, opt } );
8880  }
8881  } else {
8882  m_tokenBuffer.push_back( { TokenType::Option, next } );
8883  }
8884  }
8885  } else {
8886  m_tokenBuffer.push_back( { TokenType::Argument, next } );
8887  }
8888  }
8889  }
8890 
8891  public:
8892  explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8893 
8894  TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8895  loadBuffer();
8896  }
8897 
8898  explicit operator bool() const {
8899  return !m_tokenBuffer.empty() || it != itEnd;
8900  }
8901 
8902  auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8903 
8904  auto operator*() const -> Token {
8905  assert( !m_tokenBuffer.empty() );
8906  return m_tokenBuffer.front();
8907  }
8908 
8909  auto operator->() const -> Token const * {
8910  assert( !m_tokenBuffer.empty() );
8911  return &m_tokenBuffer.front();
8912  }
8913 
8914  auto operator++() -> TokenStream & {
8915  if( m_tokenBuffer.size() >= 2 ) {
8916  m_tokenBuffer.erase( m_tokenBuffer.begin() );
8917  } else {
8918  if( it != itEnd )
8919  ++it;
8920  loadBuffer();
8921  }
8922  return *this;
8923  }
8924  };
8925 
8926  class ResultBase {
8927  public:
8928  enum Type {
8929  Ok, LogicError, RuntimeError
8930  };
8931 
8932  protected:
8933  ResultBase( Type type ) : m_type( type ) {}
8934  virtual ~ResultBase() = default;
8935 
8936  virtual void enforceOk() const = 0;
8937 
8938  Type m_type;
8939  };
8940 
8941  template<typename T>
8942  class ResultValueBase : public ResultBase {
8943  public:
8944  auto value() const -> T const & {
8945  enforceOk();
8946  return m_value;
8947  }
8948 
8949  protected:
8950  ResultValueBase( Type type ) : ResultBase( type ) {}
8951 
8952  ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8953  if( m_type == ResultBase::Ok )
8954  new( &m_value ) T( other.m_value );
8955  }
8956 
8957  ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8958  new( &m_value ) T( value );
8959  }
8960 
8961  auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8962  if( m_type == ResultBase::Ok )
8963  m_value.~T();
8964  ResultBase::operator=(other);
8965  if( m_type == ResultBase::Ok )
8966  new( &m_value ) T( other.m_value );
8967  return *this;
8968  }
8969 
8970  ~ResultValueBase() override {
8971  if( m_type == Ok )
8972  m_value.~T();
8973  }
8974 
8975  union {
8976  T m_value;
8977  };
8978  };
8979 
8980  template<>
8981  class ResultValueBase<void> : public ResultBase {
8982  protected:
8983  using ResultBase::ResultBase;
8984  };
8985 
8986  template<typename T = void>
8987  class BasicResult : public ResultValueBase<T> {
8988  public:
8989  template<typename U>
8990  explicit BasicResult( BasicResult<U> const &other )
8991  : ResultValueBase<T>( other.type() ),
8992  m_errorMessage( other.errorMessage() )
8993  {
8994  assert( type() != ResultBase::Ok );
8995  }
8996 
8997  template<typename U>
8998  static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
8999  static auto ok() -> BasicResult { return { ResultBase::Ok }; }
9000  static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
9001  static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
9002 
9003  explicit operator bool() const { return m_type == ResultBase::Ok; }
9004  auto type() const -> ResultBase::Type { return m_type; }
9005  auto errorMessage() const -> std::string { return m_errorMessage; }
9006 
9007  protected:
9008  void enforceOk() const override {
9009 
9010  // Errors shouldn't reach this point, but if they do
9011  // the actual error message will be in m_errorMessage
9012  assert( m_type != ResultBase::LogicError );
9013  assert( m_type != ResultBase::RuntimeError );
9014  if( m_type != ResultBase::Ok )
9015  std::abort();
9016  }
9017 
9018  std::string m_errorMessage; // Only populated if resultType is an error
9019 
9020  BasicResult( ResultBase::Type type, std::string const &message )
9021  : ResultValueBase<T>(type),
9022  m_errorMessage(message)
9023  {
9024  assert( m_type != ResultBase::Ok );
9025  }
9026 
9027  using ResultValueBase<T>::ResultValueBase;
9028  using ResultBase::m_type;
9029  };
9030 
9031  enum class ParseResultType {
9032  Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9033  };
9034 
9035  class ParseState {
9036  public:
9037 
9038  ParseState( ParseResultType type, TokenStream const &remainingTokens )
9039  : m_type(type),
9040  m_remainingTokens( remainingTokens )
9041  {}
9042 
9043  auto type() const -> ParseResultType { return m_type; }
9044  auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9045 
9046  private:
9047  ParseResultType m_type;
9048  TokenStream m_remainingTokens;
9049  };
9050 
9051  using Result = BasicResult<void>;
9052  using ParserResult = BasicResult<ParseResultType>;
9053  using InternalParseResult = BasicResult<ParseState>;
9054 
9055  struct HelpColumns {
9056  std::string left;
9057  std::string right;
9058  };
9059 
9060  template<typename T>
9061  inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
9062  std::stringstream ss;
9063  ss << source;
9064  ss >> target;
9065  if( ss.fail() )
9066  return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
9067  else
9068  return ParserResult::ok( ParseResultType::Matched );
9069  }
9070  inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
9071  target = source;
9072  return ParserResult::ok( ParseResultType::Matched );
9073  }
9074  inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
9075  std::string srcLC = source;
9076  std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9077  if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9078  target = true;
9079  else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9080  target = false;
9081  else
9082  return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
9083  return ParserResult::ok( ParseResultType::Matched );
9084  }
9085 #ifdef CLARA_CONFIG_OPTIONAL_TYPE
9086  template<typename T>
9087  inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9088  T temp;
9089  auto result = convertInto( source, temp );
9090  if( result )
9091  target = std::move(temp);
9092  return result;
9093  }
9094 #endif // CLARA_CONFIG_OPTIONAL_TYPE
9095 
9096  struct NonCopyable {
9097  NonCopyable() = default;
9098  NonCopyable( NonCopyable const & ) = delete;
9099  NonCopyable( NonCopyable && ) = delete;
9100  NonCopyable &operator=( NonCopyable const & ) = delete;
9101  NonCopyable &operator=( NonCopyable && ) = delete;
9102  };
9103 
9104  struct BoundRef : NonCopyable {
9105  virtual ~BoundRef() = default;
9106  virtual auto isContainer() const -> bool { return false; }
9107  virtual auto isFlag() const -> bool { return false; }
9108  };
9109  struct BoundValueRefBase : BoundRef {
9110  virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
9111  };
9112  struct BoundFlagRefBase : BoundRef {
9113  virtual auto setFlag( bool flag ) -> ParserResult = 0;
9114  virtual auto isFlag() const -> bool { return true; }
9115  };
9116 
9117  template<typename T>
9118  struct BoundValueRef : BoundValueRefBase {
9119  T &m_ref;
9120 
9121  explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9122 
9123  auto setValue( std::string const &arg ) -> ParserResult override {
9124  return convertInto( arg, m_ref );
9125  }
9126  };
9127 
9128  template<typename T>
9129  struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9130  std::vector<T> &m_ref;
9131 
9132  explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9133 
9134  auto isContainer() const -> bool override { return true; }
9135 
9136  auto setValue( std::string const &arg ) -> ParserResult override {
9137  T temp;
9138  auto result = convertInto( arg, temp );
9139  if( result )
9140  m_ref.push_back( temp );
9141  return result;
9142  }
9143  };
9144 
9145  struct BoundFlagRef : BoundFlagRefBase {
9146  bool &m_ref;
9147 
9148  explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
9149 
9150  auto setFlag( bool flag ) -> ParserResult override {
9151  m_ref = flag;
9152  return ParserResult::ok( ParseResultType::Matched );
9153  }
9154  };
9155 
9156  template<typename ReturnType>
9157  struct LambdaInvoker {
9158  static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
9159 
9160  template<typename L, typename ArgType>
9161  static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9162  return lambda( arg );
9163  }
9164  };
9165 
9166  template<>
9167  struct LambdaInvoker<void> {
9168  template<typename L, typename ArgType>
9169  static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9170  lambda( arg );
9171  return ParserResult::ok( ParseResultType::Matched );
9172  }
9173  };
9174 
9175  template<typename ArgType, typename L>
9176  inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
9177  ArgType temp{};
9178  auto result = convertInto( arg, temp );
9179  return !result
9180  ? result
9181  : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9182  }
9183 
9184  template<typename L>
9185  struct BoundLambda : BoundValueRefBase {
9186  L m_lambda;
9187 
9188  static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9189  explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
9190 
9191  auto setValue( std::string const &arg ) -> ParserResult override {
9192  return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9193  }
9194  };
9195 
9196  template<typename L>
9197  struct BoundFlagLambda : BoundFlagRefBase {
9198  L m_lambda;
9199 
9200  static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9201  static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
9202 
9203  explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
9204 
9205  auto setFlag( bool flag ) -> ParserResult override {
9206  return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9207  }
9208  };
9209 
9210  enum class Optionality { Optional, Required };
9211 
9212  struct Parser;
9213 
9214  class ParserBase {
9215  public:
9216  virtual ~ParserBase() = default;
9217  virtual auto validate() const -> Result { return Result::ok(); }
9218  virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
9219  virtual auto cardinality() const -> size_t { return 1; }
9220 
9221  auto parse( Args const &args ) const -> InternalParseResult {
9222  return parse( args.exeName(), TokenStream( args ) );
9223  }
9224  };
9225 
9226  template<typename DerivedT>
9227  class ComposableParserImpl : public ParserBase {
9228  public:
9229  template<typename T>
9230  auto operator|( T const &other ) const -> Parser;
9231 
9232  template<typename T>
9233  auto operator+( T const &other ) const -> Parser;
9234  };
9235 
9236  // Common code and state for Args and Opts
9237  template<typename DerivedT>
9238  class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9239  protected:
9240  Optionality m_optionality = Optionality::Optional;
9241  std::shared_ptr<BoundRef> m_ref;
9242  std::string m_hint;
9243  std::string m_description;
9244 
9245  explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
9246 
9247  public:
9248  template<typename T>
9249  ParserRefImpl( T &ref, std::string const &hint )
9250  : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9251  m_hint( hint )
9252  {}
9253 
9254  template<typename LambdaT>
9255  ParserRefImpl( LambdaT const &ref, std::string const &hint )
9256  : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9257  m_hint(hint)
9258  {}
9259 
9260  auto operator()( std::string const &description ) -> DerivedT & {
9261  m_description = description;
9262  return static_cast<DerivedT &>( *this );
9263  }
9264 
9265  auto optional() -> DerivedT & {
9266  m_optionality = Optionality::Optional;
9267  return static_cast<DerivedT &>( *this );
9268  };
9269 
9270  auto required() -> DerivedT & {
9271  m_optionality = Optionality::Required;
9272  return static_cast<DerivedT &>( *this );
9273  };
9274 
9275  auto isOptional() const -> bool {
9276  return m_optionality == Optionality::Optional;
9277  }
9278 
9279  auto cardinality() const -> size_t override {
9280  if( m_ref->isContainer() )
9281  return 0;
9282  else
9283  return 1;
9284  }
9285 
9286  auto hint() const -> std::string { return m_hint; }
9287  };
9288 
9289  class ExeName : public ComposableParserImpl<ExeName> {
9290  std::shared_ptr<std::string> m_name;
9291  std::shared_ptr<BoundValueRefBase> m_ref;
9292 
9293  template<typename LambdaT>
9294  static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9295  return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9296  }
9297 
9298  public:
9299  ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
9300 
9301  explicit ExeName( std::string &ref ) : ExeName() {
9302  m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9303  }
9304 
9305  template<typename LambdaT>
9306  explicit ExeName( LambdaT const& lambda ) : ExeName() {
9307  m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9308  }
9309 
9310  // The exe name is not parsed out of the normal tokens, but is handled specially
9311  auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9312  return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9313  }
9314 
9315  auto name() const -> std::string { return *m_name; }
9316  auto set( std::string const& newName ) -> ParserResult {
9317 
9318  auto lastSlash = newName.find_last_of( "\\/" );
9319  auto filename = ( lastSlash == std::string::npos )
9320  ? newName
9321  : newName.substr( lastSlash+1 );
9322 
9323  *m_name = filename;
9324  if( m_ref )
9325  return m_ref->setValue( filename );
9326  else
9327  return ParserResult::ok( ParseResultType::Matched );
9328  }
9329  };
9330 
9331  class Arg : public ParserRefImpl<Arg> {
9332  public:
9333  using ParserRefImpl::ParserRefImpl;
9334 
9335  auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9336  auto validationResult = validate();
9337  if( !validationResult )
9338  return InternalParseResult( validationResult );
9339 
9340  auto remainingTokens = tokens;
9341  auto const &token = *remainingTokens;
9342  if( token.type != TokenType::Argument )
9343  return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9344 
9345  assert( !m_ref->isFlag() );
9346  auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9347 
9348  auto result = valueRef->setValue( remainingTokens->token );
9349  if( !result )
9350  return InternalParseResult( result );
9351  else
9352  return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9353  }
9354  };
9355 
9356  inline auto normaliseOpt( std::string const &optName ) -> std::string {
9357 #ifdef CATCH_PLATFORM_WINDOWS
9358  if( optName[0] == '/' )
9359  return "-" + optName.substr( 1 );
9360  else
9361 #endif
9362  return optName;
9363  }
9364 
9365  class Opt : public ParserRefImpl<Opt> {
9366  protected:
9367  std::vector<std::string> m_optNames;
9368 
9369  public:
9370  template<typename LambdaT>
9371  explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9372 
9373  explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9374 
9375  template<typename LambdaT>
9376  Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9377 
9378  template<typename T>
9379  Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9380 
9381  auto operator[]( std::string const &optName ) -> Opt & {
9382  m_optNames.push_back( optName );
9383  return *this;
9384  }
9385 
9386  auto getHelpColumns() const -> std::vector<HelpColumns> {
9387  std::ostringstream oss;
9388  bool first = true;
9389  for( auto const &opt : m_optNames ) {
9390  if (first)
9391  first = false;
9392  else
9393  oss << ", ";
9394  oss << opt;
9395  }
9396  if( !m_hint.empty() )
9397  oss << " <" << m_hint << ">";
9398  return { { oss.str(), m_description } };
9399  }
9400 
9401  auto isMatch( std::string const &optToken ) const -> bool {
9402  auto normalisedToken = normaliseOpt( optToken );
9403  for( auto const &name : m_optNames ) {
9404  if( normaliseOpt( name ) == normalisedToken )
9405  return true;
9406  }
9407  return false;
9408  }
9409 
9410  using ParserBase::parse;
9411 
9412  auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9413  auto validationResult = validate();
9414  if( !validationResult )
9415  return InternalParseResult( validationResult );
9416 
9417  auto remainingTokens = tokens;
9418  if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9419  auto const &token = *remainingTokens;
9420  if( isMatch(token.token ) ) {
9421  if( m_ref->isFlag() ) {
9422  auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9423  auto result = flagRef->setFlag( true );
9424  if( !result )
9425  return InternalParseResult( result );
9426  if( result.value() == ParseResultType::ShortCircuitAll )
9427  return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9428  } else {
9429  auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9430  ++remainingTokens;
9431  if( !remainingTokens )
9432  return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9433  auto const &argToken = *remainingTokens;
9434  if( argToken.type != TokenType::Argument )
9435  return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9436  auto result = valueRef->setValue( argToken.token );
9437  if( !result )
9438  return InternalParseResult( result );
9439  if( result.value() == ParseResultType::ShortCircuitAll )
9440  return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9441  }
9442  return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9443  }
9444  }
9445  return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9446  }
9447 
9448  auto validate() const -> Result override {
9449  if( m_optNames.empty() )
9450  return Result::logicError( "No options supplied to Opt" );
9451  for( auto const &name : m_optNames ) {
9452  if( name.empty() )
9453  return Result::logicError( "Option name cannot be empty" );
9454 #ifdef CATCH_PLATFORM_WINDOWS
9455  if( name[0] != '-' && name[0] != '/' )
9456  return Result::logicError( "Option name must begin with '-' or '/'" );
9457 #else
9458  if( name[0] != '-' )
9459  return Result::logicError( "Option name must begin with '-'" );
9460 #endif
9461  }
9462  return ParserRefImpl::validate();
9463  }
9464  };
9465 
9466  struct Help : Opt {
9467  Help( bool &showHelpFlag )
9468  : Opt([&]( bool flag ) {
9469  showHelpFlag = flag;
9470  return ParserResult::ok( ParseResultType::ShortCircuitAll );
9471  })
9472  {
9473  static_cast<Opt &>( *this )
9474  ("display usage information")
9475  ["-?"]["-h"]["--help"]
9476  .optional();
9477  }
9478  };
9479 
9480  struct Parser : ParserBase {
9481 
9482  mutable ExeName m_exeName;
9483  std::vector<Opt> m_options;
9484  std::vector<Arg> m_args;
9485 
9486  auto operator|=( ExeName const &exeName ) -> Parser & {
9487  m_exeName = exeName;
9488  return *this;
9489  }
9490 
9491  auto operator|=( Arg const &arg ) -> Parser & {
9492  m_args.push_back(arg);
9493  return *this;
9494  }
9495 
9496  auto operator|=( Opt const &opt ) -> Parser & {
9497  m_options.push_back(opt);
9498  return *this;
9499  }
9500 
9501  auto operator|=( Parser const &other ) -> Parser & {
9502  m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9503  m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9504  return *this;
9505  }
9506 
9507  template<typename T>
9508  auto operator|( T const &other ) const -> Parser {
9509  return Parser( *this ) |= other;
9510  }
9511 
9512  // Forward deprecated interface with '+' instead of '|'
9513  template<typename T>
9514  auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9515  template<typename T>
9516  auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9517 
9518  auto getHelpColumns() const -> std::vector<HelpColumns> {
9519  std::vector<HelpColumns> cols;
9520  for (auto const &o : m_options) {
9521  auto childCols = o.getHelpColumns();
9522  cols.insert( cols.end(), childCols.begin(), childCols.end() );
9523  }
9524  return cols;
9525  }
9526 
9527  void writeToStream( std::ostream &os ) const {
9528  if (!m_exeName.name().empty()) {
9529  os << "usage:\n" << " " << m_exeName.name() << " ";
9530  bool required = true, first = true;
9531  for( auto const &arg : m_args ) {
9532  if (first)
9533  first = false;
9534  else
9535  os << " ";
9536  if( arg.isOptional() && required ) {
9537  os << "[";
9538  required = false;
9539  }
9540  os << "<" << arg.hint() << ">";
9541  if( arg.cardinality() == 0 )
9542  os << " ... ";
9543  }
9544  if( !required )
9545  os << "]";
9546  if( !m_options.empty() )
9547  os << " options";
9548  os << "\n\nwhere options are:" << std::endl;
9549  }
9550 
9551  auto rows = getHelpColumns();
9552  size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9553  size_t optWidth = 0;
9554  for( auto const &cols : rows )
9555  optWidth = (std::max)(optWidth, cols.left.size() + 2);
9556 
9557  optWidth = (std::min)(optWidth, consoleWidth/2);
9558 
9559  for( auto const &cols : rows ) {
9560  auto row =
9561  TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9562  TextFlow::Spacer(4) +
9563  TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9564  os << row << std::endl;
9565  }
9566  }
9567 
9568  friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9569  parser.writeToStream( os );
9570  return os;
9571  }
9572 
9573  auto validate() const -> Result override {
9574  for( auto const &opt : m_options ) {
9575  auto result = opt.validate();
9576  if( !result )
9577  return result;
9578  }
9579  for( auto const &arg : m_args ) {
9580  auto result = arg.validate();
9581  if( !result )
9582  return result;
9583  }
9584  return Result::ok();
9585  }
9586 
9587  using ParserBase::parse;
9588 
9589  auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9590 
9591  struct ParserInfo {
9592  ParserBase const* parser = nullptr;
9593  size_t count = 0;
9594  };
9595  const size_t totalParsers = m_options.size() + m_args.size();
9596  assert( totalParsers < 512 );
9597  // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9598  ParserInfo parseInfos[512];
9599 
9600  {
9601  size_t i = 0;
9602  for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9603  for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9604  }
9605 
9606  m_exeName.set( exeName );
9607 
9608  auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9609  while( result.value().remainingTokens() ) {
9610  bool tokenParsed = false;
9611 
9612  for( size_t i = 0; i < totalParsers; ++i ) {
9613  auto& parseInfo = parseInfos[i];
9614  if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9615  result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9616  if (!result)
9617  return result;
9618  if (result.value().type() != ParseResultType::NoMatch) {
9619  tokenParsed = true;
9620  ++parseInfo.count;
9621  break;
9622  }
9623  }
9624  }
9625 
9626  if( result.value().type() == ParseResultType::ShortCircuitAll )
9627  return result;
9628  if( !tokenParsed )
9629  return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9630  }
9631  // !TBD Check missing required options
9632  return result;
9633  }
9634  };
9635 
9636  template<typename DerivedT>
9637  template<typename T>
9638  auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9639  return Parser() | static_cast<DerivedT const &>( *this ) | other;
9640  }
9641 } // namespace detail
9642 
9643 // A Combined parser
9644 using detail::Parser;
9645 
9646 // A parser for options
9647 using detail::Opt;
9648 
9649 // A parser for arguments
9650 using detail::Arg;
9651 
9652 // Wrapper for argc, argv from main()
9653 using detail::Args;
9654 
9655 // Specifies the name of the executable
9656 using detail::ExeName;
9657 
9658 // Convenience wrapper for option parser that specifies the help option
9659 using detail::Help;
9660 
9661 // enum of result types from a parse
9662 using detail::ParseResultType;
9663 
9664 // Result type for parser operation
9665 using detail::ParserResult;
9666 
9667 }} // namespace Catch::clara
9668 
9669 // end clara.hpp
9670 #ifdef __clang__
9671 #pragma clang diagnostic pop
9672 #endif
9673 
9674 // Restore Clara's value for console width, if present
9675 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9676 #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9677 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9678 #endif
9679 
9680 // end catch_clara.h
9681 namespace Catch {
9682 
9683  clara::Parser makeCommandLineParser( ConfigData& config );
9684 
9685 } // end namespace Catch
9686 
9687 // end catch_commandline.h
9688 #include <fstream>
9689 #include <ctime>
9690 
9691 namespace Catch {
9692 
9693  clara::Parser makeCommandLineParser( ConfigData& config ) {
9694 
9695  using namespace clara;
9696 
9697  auto const setWarning = [&]( std::string const& warning ) {
9698  auto warningSet = [&]() {
9699  if( warning == "NoAssertions" )
9700  return WarnAbout::NoAssertions;
9701 
9702  if ( warning == "NoTests" )
9703  return WarnAbout::NoTests;
9704 
9705  return WarnAbout::Nothing;
9706  }();
9707 
9708  if (warningSet == WarnAbout::Nothing)
9709  return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9710  config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9711  return ParserResult::ok( ParseResultType::Matched );
9712  };
9713  auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9714  std::ifstream f( filename.c_str() );
9715  if( !f.is_open() )
9716  return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9717 
9718  std::string line;
9719  while( std::getline( f, line ) ) {
9720  line = trim(line);
9721  if( !line.empty() && !startsWith( line, '#' ) ) {
9722  if( !startsWith( line, '"' ) )
9723  line = '"' + line + '"';
9724  config.testsOrTags.push_back( line );
9725  config.testsOrTags.emplace_back( "," );
9726  }
9727  }
9728  //Remove comma in the end
9729  if(!config.testsOrTags.empty())
9730  config.testsOrTags.erase( config.testsOrTags.end()-1 );
9731 
9732  return ParserResult::ok( ParseResultType::Matched );
9733  };
9734  auto const setTestOrder = [&]( std::string const& order ) {
9735  if( startsWith( "declared", order ) )
9736  config.runOrder = RunTests::InDeclarationOrder;
9737  else if( startsWith( "lexical", order ) )
9738  config.runOrder = RunTests::InLexicographicalOrder;
9739  else if( startsWith( "random", order ) )
9740  config.runOrder = RunTests::InRandomOrder;
9741  else
9742  return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9743  return ParserResult::ok( ParseResultType::Matched );
9744  };
9745  auto const setRngSeed = [&]( std::string const& seed ) {
9746  if( seed != "time" )
9747  return clara::detail::convertInto( seed, config.rngSeed );
9748  config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9749  return ParserResult::ok( ParseResultType::Matched );
9750  };
9751  auto const setColourUsage = [&]( std::string const& useColour ) {
9752  auto mode = toLower( useColour );
9753 
9754  if( mode == "yes" )
9755  config.useColour = UseColour::Yes;
9756  else if( mode == "no" )
9757  config.useColour = UseColour::No;
9758  else if( mode == "auto" )
9759  config.useColour = UseColour::Auto;
9760  else
9761  return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9762  return ParserResult::ok( ParseResultType::Matched );
9763  };
9764  auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9765  auto keypressLc = toLower( keypress );
9766  if (keypressLc == "never")
9767  config.waitForKeypress = WaitForKeypress::Never;
9768  else if( keypressLc == "start" )
9769  config.waitForKeypress = WaitForKeypress::BeforeStart;
9770  else if( keypressLc == "exit" )
9771  config.waitForKeypress = WaitForKeypress::BeforeExit;
9772  else if( keypressLc == "both" )
9773  config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9774  else
9775  return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
9776  return ParserResult::ok( ParseResultType::Matched );
9777  };
9778  auto const setVerbosity = [&]( std::string const& verbosity ) {
9779  auto lcVerbosity = toLower( verbosity );
9780  if( lcVerbosity == "quiet" )
9781  config.verbosity = Verbosity::Quiet;
9782  else if( lcVerbosity == "normal" )
9783  config.verbosity = Verbosity::Normal;
9784  else if( lcVerbosity == "high" )
9785  config.verbosity = Verbosity::High;
9786  else
9787  return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9788  return ParserResult::ok( ParseResultType::Matched );
9789  };
9790  auto const setReporter = [&]( std::string const& reporter ) {
9791  IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9792 
9793  auto lcReporter = toLower( reporter );
9794  auto result = factories.find( lcReporter );
9795 
9796  if( factories.end() != result )
9797  config.reporterName = lcReporter;
9798  else
9799  return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9800  return ParserResult::ok( ParseResultType::Matched );
9801  };
9802 
9803  auto cli
9804  = ExeName( config.processName )
9805  | Help( config.showHelp )
9806  | Opt( config.listTests )
9807  ["-l"]["--list-tests"]
9808  ( "list all/matching test cases" )
9809  | Opt( config.listTags )
9810  ["-t"]["--list-tags"]
9811  ( "list all/matching tags" )
9812  | Opt( config.showSuccessfulTests )
9813  ["-s"]["--success"]
9814  ( "include successful tests in output" )
9815  | Opt( config.shouldDebugBreak )
9816  ["-b"]["--break"]
9817  ( "break into debugger on failure" )
9818  | Opt( config.noThrow )
9819  ["-e"]["--nothrow"]
9820  ( "skip exception tests" )
9821  | Opt( config.showInvisibles )
9822  ["-i"]["--invisibles"]
9823  ( "show invisibles (tabs, newlines)" )
9824  | Opt( config.outputFilename, "filename" )
9825  ["-o"]["--out"]
9826  ( "output filename" )
9827  | Opt( setReporter, "name" )
9828  ["-r"]["--reporter"]
9829  ( "reporter to use (defaults to console)" )
9830  | Opt( config.name, "name" )
9831  ["-n"]["--name"]
9832  ( "suite name" )
9833  | Opt( [&]( bool ){ config.abortAfter = 1; } )
9834  ["-a"]["--abort"]
9835  ( "abort at first failure" )
9836  | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9837  ["-x"]["--abortx"]
9838  ( "abort after x failures" )
9839  | Opt( setWarning, "warning name" )
9840  ["-w"]["--warn"]
9841  ( "enable warnings" )
9842  | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9843  ["-d"]["--durations"]
9844  ( "show test durations" )
9845  | Opt( config.minDuration, "seconds" )
9846  ["-D"]["--min-duration"]
9847  ( "show test durations for tests taking at least the given number of seconds" )
9848  | Opt( loadTestNamesFromFile, "filename" )
9849  ["-f"]["--input-file"]
9850  ( "load test names to run from a file" )
9851  | Opt( config.filenamesAsTags )
9852  ["-#"]["--filenames-as-tags"]
9853  ( "adds a tag for the filename" )
9854  | Opt( config.sectionsToRun, "section name" )
9855  ["-c"]["--section"]
9856  ( "specify section to run" )
9857  | Opt( setVerbosity, "quiet|normal|high" )
9858  ["-v"]["--verbosity"]
9859  ( "set output verbosity" )
9860  | Opt( config.listTestNamesOnly )
9861  ["--list-test-names-only"]
9862  ( "list all/matching test cases names only" )
9863  | Opt( config.listReporters )
9864  ["--list-reporters"]
9865  ( "list all reporters" )
9866  | Opt( setTestOrder, "decl|lex|rand" )
9867  ["--order"]
9868  ( "test case order (defaults to decl)" )
9869  | Opt( setRngSeed, "'time'|number" )
9870  ["--rng-seed"]
9871  ( "set a specific seed for random numbers" )
9872  | Opt( setColourUsage, "yes|no" )
9873  ["--use-colour"]
9874  ( "should output be colourised" )
9875  | Opt( config.libIdentify )
9876  ["--libidentify"]
9877  ( "report name and version according to libidentify standard" )
9878  | Opt( setWaitForKeypress, "never|start|exit|both" )
9879  ["--wait-for-keypress"]
9880  ( "waits for a keypress before exiting" )
9881  | Opt( config.benchmarkSamples, "samples" )
9882  ["--benchmark-samples"]
9883  ( "number of samples to collect (default: 100)" )
9884  | Opt( config.benchmarkResamples, "resamples" )
9885  ["--benchmark-resamples"]
9886  ( "number of resamples for the bootstrap (default: 100000)" )
9887  | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9888  ["--benchmark-confidence-interval"]
9889  ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9890  | Opt( config.benchmarkNoAnalysis )
9891  ["--benchmark-no-analysis"]
9892  ( "perform only measurements; do not perform any analysis" )
9893  | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
9894  ["--benchmark-warmup-time"]
9895  ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
9896  | Arg( config.testsOrTags, "test name|pattern|tags" )
9897  ( "which test or tests to use" );
9898 
9899  return cli;
9900  }
9901 
9902 } // end namespace Catch
9903 // end catch_commandline.cpp
9904 // start catch_common.cpp
9905 
9906 #include <cstring>
9907 #include <ostream>
9908 
9909 namespace Catch {
9910 
9911  bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9912  return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9913  }
9914  bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9915  // We can assume that the same file will usually have the same pointer.
9916  // Thus, if the pointers are the same, there is no point in calling the strcmp
9917  return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9918  }
9919 
9920  std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9921 #ifndef __GNUG__
9922  os << info.file << '(' << info.line << ')';
9923 #else
9924  os << info.file << ':' << info.line;
9925 #endif
9926  return os;
9927  }
9928 
9929  std::string StreamEndStop::operator+() const {
9930  return std::string();
9931  }
9932 
9933  NonCopyable::NonCopyable() = default;
9934  NonCopyable::~NonCopyable() = default;
9935 
9936 }
9937 // end catch_common.cpp
9938 // start catch_config.cpp
9939 
9940 namespace Catch {
9941 
9942  Config::Config( ConfigData const& data )
9943  : m_data( data ),
9944  m_stream( openStream() )
9945  {
9946  // We need to trim filter specs to avoid trouble with superfluous
9947  // whitespace (esp. important for bdd macros, as those are manually
9948  // aligned with whitespace).
9949 
9950  for (auto& elem : m_data.testsOrTags) {
9951  elem = trim(elem);
9952  }
9953  for (auto& elem : m_data.sectionsToRun) {
9954  elem = trim(elem);
9955  }
9956 
9957  TestSpecParser parser(ITagAliasRegistry::get());
9958  if (!m_data.testsOrTags.empty()) {
9959  m_hasTestFilters = true;
9960  for (auto const& testOrTags : m_data.testsOrTags) {
9961  parser.parse(testOrTags);
9962  }
9963  }
9964  m_testSpec = parser.testSpec();
9965  }
9966 
9967  std::string const& Config::getFilename() const {
9968  return m_data.outputFilename ;
9969  }
9970 
9971  bool Config::listTests() const { return m_data.listTests; }
9972  bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
9973  bool Config::listTags() const { return m_data.listTags; }
9974  bool Config::listReporters() const { return m_data.listReporters; }
9975 
9976  std::string Config::getProcessName() const { return m_data.processName; }
9977  std::string const& Config::getReporterName() const { return m_data.reporterName; }
9978 
9979  std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
9980  std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9981 
9982  TestSpec const& Config::testSpec() const { return m_testSpec; }
9983  bool Config::hasTestFilters() const { return m_hasTestFilters; }
9984 
9985  bool Config::showHelp() const { return m_data.showHelp; }
9986 
9987  // IConfig interface
9988  bool Config::allowThrows() const { return !m_data.noThrow; }
9989  std::ostream& Config::stream() const { return m_stream->stream(); }
9990  std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
9991  bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
9992  bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
9993  bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
9994  ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
9995  double Config::minDuration() const { return m_data.minDuration; }
9996  RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
9997  unsigned int Config::rngSeed() const { return m_data.rngSeed; }
9998  UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
9999  bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10000  int Config::abortAfter() const { return m_data.abortAfter; }
10001  bool Config::showInvisibles() const { return m_data.showInvisibles; }
10002  Verbosity Config::verbosity() const { return m_data.verbosity; }
10003 
10004  bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10005  int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10006  double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
10007  unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10008  std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10009 
10010  IStream const* Config::openStream() {
10011  return Catch::makeStream(m_data.outputFilename);
10012  }
10013 
10014 } // end namespace Catch
10015 // end catch_config.cpp
10016 // start catch_console_colour.cpp
10017 
10018 #if defined(__clang__)
10019 # pragma clang diagnostic push
10020 # pragma clang diagnostic ignored "-Wexit-time-destructors"
10021 #endif
10022 
10023 // start catch_errno_guard.h
10024 
10025 namespace Catch {
10026 
10027  class ErrnoGuard {
10028  public:
10029  ErrnoGuard();
10030  ~ErrnoGuard();
10031  private:
10032  int m_oldErrno;
10033  };
10034 
10035 }
10036 
10037 // end catch_errno_guard.h
10038 // start catch_windows_h_proxy.h
10039 
10040 
10041 #if defined(CATCH_PLATFORM_WINDOWS)
10042 
10043 #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10044 # define CATCH_DEFINED_NOMINMAX
10045 # define NOMINMAX
10046 #endif
10047 #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10048 # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10049 # define WIN32_LEAN_AND_MEAN
10050 #endif
10051 
10052 #ifdef __AFXDLL
10053 #include <AfxWin.h>
10054 #else
10055 #include <windows.h>
10056 #endif
10057 
10058 #ifdef CATCH_DEFINED_NOMINMAX
10059 # undef NOMINMAX
10060 #endif
10061 #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10062 # undef WIN32_LEAN_AND_MEAN
10063 #endif
10064 
10065 #endif // defined(CATCH_PLATFORM_WINDOWS)
10066 
10067 // end catch_windows_h_proxy.h
10068 #include <sstream>
10069 
10070 namespace Catch {
10071  namespace {
10072 
10073  struct IColourImpl {
10074  virtual ~IColourImpl() = default;
10075  virtual void use( Colour::Code _colourCode ) = 0;
10076  };
10077 
10078  struct NoColourImpl : IColourImpl {
10079  void use( Colour::Code ) override {}
10080 
10081  static IColourImpl* instance() {
10082  static NoColourImpl s_instance;
10083  return &s_instance;
10084  }
10085  };
10086 
10087  } // anon namespace
10088 } // namespace Catch
10089 
10090 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10091 # ifdef CATCH_PLATFORM_WINDOWS
10092 # define CATCH_CONFIG_COLOUR_WINDOWS
10093 # else
10094 # define CATCH_CONFIG_COLOUR_ANSI
10095 # endif
10096 #endif
10097 
10098 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS )
10099 
10100 namespace Catch {
10101 namespace {
10102 
10103  class Win32ColourImpl : public IColourImpl {
10104  public:
10105  Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10106  {
10107  CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10108  GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10109  originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10110  originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10111  }
10112 
10113  void use( Colour::Code _colourCode ) override {
10114  switch( _colourCode ) {
10115  case Colour::None: return setTextAttribute( originalForegroundAttributes );
10116  case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10117  case Colour::Red: return setTextAttribute( FOREGROUND_RED );
10118  case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
10119  case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
10120  case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10121  case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10122  case Colour::Grey: return setTextAttribute( 0 );
10123 
10124  case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
10125  case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10126  case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10127  case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10128  case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10129 
10130  case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10131 
10132  default:
10133  CATCH_ERROR( "Unknown colour requested" );
10134  }
10135  }
10136 
10137  private:
10138  void setTextAttribute( WORD _textAttribute ) {
10139  SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10140  }
10141  HANDLE stdoutHandle;
10142  WORD originalForegroundAttributes;
10143  WORD originalBackgroundAttributes;
10144  };
10145 
10146  IColourImpl* platformColourInstance() {
10147  static Win32ColourImpl s_instance;
10148 
10149  IConfigPtr config = getCurrentContext().getConfig();
10150  UseColour::YesOrNo colourMode = config
10151  ? config->useColour()
10152  : UseColour::Auto;
10153  if( colourMode == UseColour::Auto )
10154  colourMode = UseColour::Yes;
10155  return colourMode == UseColour::Yes
10156  ? &s_instance
10157  : NoColourImpl::instance();
10158  }
10159 
10160 } // end anon namespace
10161 } // end namespace Catch
10162 
10163 #elif defined( CATCH_CONFIG_COLOUR_ANSI )
10164 
10165 #include <unistd.h>
10166 
10167 namespace Catch {
10168 namespace {
10169 
10170  // use POSIX/ ANSI console terminal codes
10171  // Thanks to Adam Strzelecki for original contribution
10172  // (http://github.com/nanoant)
10173  // https://github.com/philsquared/Catch/pull/131
10174  class PosixColourImpl : public IColourImpl {
10175  public:
10176  void use( Colour::Code _colourCode ) override {
10177  switch( _colourCode ) {
10178  case Colour::None:
10179  case Colour::White: return setColour( "[0m" );
10180  case Colour::Red: return setColour( "[0;31m" );
10181  case Colour::Green: return setColour( "[0;32m" );
10182  case Colour::Blue: return setColour( "[0;34m" );
10183  case Colour::Cyan: return setColour( "[0;36m" );
10184  case Colour::Yellow: return setColour( "[0;33m" );
10185  case Colour::Grey: return setColour( "[1;30m" );
10186 
10187  case Colour::LightGrey: return setColour( "[0;37m" );
10188  case Colour::BrightRed: return setColour( "[1;31m" );
10189  case Colour::BrightGreen: return setColour( "[1;32m" );
10190  case Colour::BrightWhite: return setColour( "[1;37m" );
10191  case Colour::BrightYellow: return setColour( "[1;33m" );
10192 
10193  case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10194  default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
10195  }
10196  }
10197  static IColourImpl* instance() {
10198  static PosixColourImpl s_instance;
10199  return &s_instance;
10200  }
10201 
10202  private:
10203  void setColour( const char* _escapeCode ) {
10204  getCurrentContext().getConfig()->stream()
10205  << '\033' << _escapeCode;
10206  }
10207  };
10208 
10209  bool useColourOnPlatform() {
10210  return
10211 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10212  !isDebuggerActive() &&
10213 #endif
10214 #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10215  isatty(STDOUT_FILENO)
10216 #else
10217  false
10218 #endif
10219  ;
10220  }
10221  IColourImpl* platformColourInstance() {
10222  ErrnoGuard guard;
10223  IConfigPtr config = getCurrentContext().getConfig();
10224  UseColour::YesOrNo colourMode = config
10225  ? config->useColour()
10226  : UseColour::Auto;
10227  if( colourMode == UseColour::Auto )
10228  colourMode = useColourOnPlatform()
10229  ? UseColour::Yes
10230  : UseColour::No;
10231  return colourMode == UseColour::Yes
10232  ? PosixColourImpl::instance()
10233  : NoColourImpl::instance();
10234  }
10235 
10236 } // end anon namespace
10237 } // end namespace Catch
10238 
10239 #else // not Windows or ANSI
10240 
10241 namespace Catch {
10242 
10243  static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10244 
10245 } // end namespace Catch
10246 
10247 #endif // Windows/ ANSI/ None
10248 
10249 namespace Catch {
10250 
10251  Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10252  Colour::Colour( Colour&& other ) noexcept {
10253  m_moved = other.m_moved;
10254  other.m_moved = true;
10255  }
10256  Colour& Colour::operator=( Colour&& other ) noexcept {
10257  m_moved = other.m_moved;
10258  other.m_moved = true;
10259  return *this;
10260  }
10261 
10262  Colour::~Colour(){ if( !m_moved ) use( None ); }
10263 
10264  void Colour::use( Code _colourCode ) {
10265  static IColourImpl* impl = platformColourInstance();
10266  // Strictly speaking, this cannot possibly happen.
10267  // However, under some conditions it does happen (see #1626),
10268  // and this change is small enough that we can let practicality
10269  // triumph over purity in this case.
10270  if (impl != nullptr) {
10271  impl->use( _colourCode );
10272  }
10273  }
10274 
10275  std::ostream& operator << ( std::ostream& os, Colour const& ) {
10276  return os;
10277  }
10278 
10279 } // end namespace Catch
10280 
10281 #if defined(__clang__)
10282 # pragma clang diagnostic pop
10283 #endif
10284 
10285 // end catch_console_colour.cpp
10286 // start catch_context.cpp
10287 
10288 namespace Catch {
10289 
10290  class Context : public IMutableContext, NonCopyable {
10291 
10292  public: // IContext
10293  IResultCapture* getResultCapture() override {
10294  return m_resultCapture;
10295  }
10296  IRunner* getRunner() override {
10297  return m_runner;
10298  }
10299 
10300  IConfigPtr const& getConfig() const override {
10301  return m_config;
10302  }
10303 
10304  ~Context() override;
10305 
10306  public: // IMutableContext
10307  void setResultCapture( IResultCapture* resultCapture ) override {
10308  m_resultCapture = resultCapture;
10309  }
10310  void setRunner( IRunner* runner ) override {
10311  m_runner = runner;
10312  }
10313  void setConfig( IConfigPtr const& config ) override {
10314  m_config = config;
10315  }
10316 
10317  friend IMutableContext& getCurrentMutableContext();
10318 
10319  private:
10320  IConfigPtr m_config;
10321  IRunner* m_runner = nullptr;
10322  IResultCapture* m_resultCapture = nullptr;
10323  };
10324 
10325  IMutableContext *IMutableContext::currentContext = nullptr;
10326 
10327  void IMutableContext::createContext()
10328  {
10329  currentContext = new Context();
10330  }
10331 
10332  void cleanUpContext() {
10333  delete IMutableContext::currentContext;
10334  IMutableContext::currentContext = nullptr;
10335  }
10336  IContext::~IContext() = default;
10337  IMutableContext::~IMutableContext() = default;
10338  Context::~Context() = default;
10339 
10340  SimplePcg32& rng() {
10341  static SimplePcg32 s_rng;
10342  return s_rng;
10343  }
10344 
10345 }
10346 // end catch_context.cpp
10347 // start catch_debug_console.cpp
10348 
10349 // start catch_debug_console.h
10350 
10351 #include <string>
10352 
10353 namespace Catch {
10354  void writeToDebugConsole( std::string const& text );
10355 }
10356 
10357 // end catch_debug_console.h
10358 #if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10359 #include <android/log.h>
10360 
10361  namespace Catch {
10362  void writeToDebugConsole( std::string const& text ) {
10363  __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
10364  }
10365  }
10366 
10367 #elif defined(CATCH_PLATFORM_WINDOWS)
10368 
10369  namespace Catch {
10370  void writeToDebugConsole( std::string const& text ) {
10371  ::OutputDebugStringA( text.c_str() );
10372  }
10373  }
10374 
10375 #else
10376 
10377  namespace Catch {
10378  void writeToDebugConsole( std::string const& text ) {
10379  // !TBD: Need a version for Mac/ XCode and other IDEs
10380  Catch::cout() << text;
10381  }
10382  }
10383 
10384 #endif // Platform
10385 // end catch_debug_console.cpp
10386 // start catch_debugger.cpp
10387 
10388 #if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10389 
10390 # include <cassert>
10391 # include <sys/types.h>
10392 # include <unistd.h>
10393 # include <cstddef>
10394 # include <ostream>
10395 
10396 #ifdef __apple_build_version__
10397  // These headers will only compile with AppleClang (XCode)
10398  // For other compilers (Clang, GCC, ... ) we need to exclude them
10399 # include <sys/sysctl.h>
10400 #endif
10401 
10402  namespace Catch {
10403  #ifdef __apple_build_version__
10404  // The following function is taken directly from the following technical note:
10405  // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10406 
10407  // Returns true if the current process is being debugged (either
10408  // running under the debugger or has a debugger attached post facto).
10409  bool isDebuggerActive(){
10410  int mib[4];
10411  struct kinfo_proc info;
10412  std::size_t size;
10413 
10414  // Initialize the flags so that, if sysctl fails for some bizarre
10415  // reason, we get a predictable result.
10416 
10417  info.kp_proc.p_flag = 0;
10418 
10419  // Initialize mib, which tells sysctl the info we want, in this case
10420  // we're looking for information about a specific process ID.
10421 
10422  mib[0] = CTL_KERN;
10423  mib[1] = KERN_PROC;
10424  mib[2] = KERN_PROC_PID;
10425  mib[3] = getpid();
10426 
10427  // Call sysctl.
10428 
10429  size = sizeof(info);
10430  if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10431  Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10432  return false;
10433  }
10434 
10435  // We're being debugged if the P_TRACED flag is set.
10436 
10437  return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10438  }
10439  #else
10440  bool isDebuggerActive() {
10441  // We need to find another way to determine this for non-appleclang compilers on macOS
10442  return false;
10443  }
10444  #endif
10445  } // namespace Catch
10446 
10447 #elif defined(CATCH_PLATFORM_LINUX)
10448  #include <fstream>
10449  #include <string>
10450 
10451  namespace Catch{
10452  // The standard POSIX way of detecting a debugger is to attempt to
10453  // ptrace() the process, but this needs to be done from a child and not
10454  // this process itself to still allow attaching to this process later
10455  // if wanted, so is rather heavy. Under Linux we have the PID of the
10456  // "debugger" (which doesn't need to be gdb, of course, it could also
10457  // be strace, for example) in /proc/$PID/status, so just get it from
10458  // there instead.
10459  bool isDebuggerActive(){
10460  // Libstdc++ has a bug, where std::ifstream sets errno to 0
10461  // This way our users can properly assert over errno values
10462  ErrnoGuard guard;
10463  std::ifstream in("/proc/self/status");
10464  for( std::string line; std::getline(in, line); ) {
10465  static const int PREFIX_LEN = 11;
10466  if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10467  // We're traced if the PID is not 0 and no other PID starts
10468  // with 0 digit, so it's enough to check for just a single
10469  // character.
10470  return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10471  }
10472  }
10473 
10474  return false;
10475  }
10476  } // namespace Catch
10477 #elif defined(_MSC_VER)
10478  extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10479  namespace Catch {
10480  bool isDebuggerActive() {
10481  return IsDebuggerPresent() != 0;
10482  }
10483  }
10484 #elif defined(__MINGW32__)
10485  extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10486  namespace Catch {
10487  bool isDebuggerActive() {
10488  return IsDebuggerPresent() != 0;
10489  }
10490  }
10491 #else
10492  namespace Catch {
10493  bool isDebuggerActive() { return false; }
10494  }
10495 #endif // Platform
10496 // end catch_debugger.cpp
10497 // start catch_decomposer.cpp
10498 
10499 namespace Catch {
10500 
10501  ITransientExpression::~ITransientExpression() = default;
10502 
10503  void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10504  if( lhs.size() + rhs.size() < 40 &&
10505  lhs.find('\n') == std::string::npos &&
10506  rhs.find('\n') == std::string::npos )
10507  os << lhs << " " << op << " " << rhs;
10508  else
10509  os << lhs << "\n" << op << "\n" << rhs;
10510  }
10511 }
10512 // end catch_decomposer.cpp
10513 // start catch_enforce.cpp
10514 
10515 #include <stdexcept>
10516 
10517 namespace Catch {
10518 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10519  [[noreturn]]
10520  void throw_exception(std::exception const& e) {
10521  Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10522  << "The message was: " << e.what() << '\n';
10523  std::terminate();
10524  }
10525 #endif
10526 
10527  [[noreturn]]
10528  void throw_logic_error(std::string const& msg) {
10529  throw_exception(std::logic_error(msg));
10530  }
10531 
10532  [[noreturn]]
10533  void throw_domain_error(std::string const& msg) {
10534  throw_exception(std::domain_error(msg));
10535  }
10536 
10537  [[noreturn]]
10538  void throw_runtime_error(std::string const& msg) {
10539  throw_exception(std::runtime_error(msg));
10540  }
10541 
10542 } // namespace Catch;
10543 // end catch_enforce.cpp
10544 // start catch_enum_values_registry.cpp
10545 // start catch_enum_values_registry.h
10546 
10547 #include <vector>
10548 #include <memory>
10549 
10550 namespace Catch {
10551 
10552  namespace Detail {
10553 
10554  std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10555 
10556  class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10557 
10558  std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10559 
10560  EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10561  };
10562 
10563  std::vector<StringRef> parseEnums( StringRef enums );
10564 
10565  } // Detail
10566 
10567 } // Catch
10568 
10569 // end catch_enum_values_registry.h
10570 
10571 #include <map>
10572 #include <cassert>
10573 
10574 namespace Catch {
10575 
10576  IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10577 
10578  namespace Detail {
10579 
10580  namespace {
10581  // Extracts the actual name part of an enum instance
10582  // In other words, it returns the Blue part of Bikeshed::Colour::Blue
10583  StringRef extractInstanceName(StringRef enumInstance) {
10584  // Find last occurrence of ":"
10585  size_t name_start = enumInstance.size();
10586  while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10587  --name_start;
10588  }
10589  return enumInstance.substr(name_start, enumInstance.size() - name_start);
10590  }
10591  }
10592 
10593  std::vector<StringRef> parseEnums( StringRef enums ) {
10594  auto enumValues = splitStringRef( enums, ',' );
10595  std::vector<StringRef> parsed;
10596  parsed.reserve( enumValues.size() );
10597  for( auto const& enumValue : enumValues ) {
10598  parsed.push_back(trim(extractInstanceName(enumValue)));
10599  }
10600  return parsed;
10601  }
10602 
10603  EnumInfo::~EnumInfo() {}
10604 
10605  StringRef EnumInfo::lookup( int value ) const {
10606  for( auto const& valueToName : m_values ) {
10607  if( valueToName.first == value )
10608  return valueToName.second;
10609  }
10610  return "{** unexpected enum value **}"_sr;
10611  }
10612 
10613  std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10614  std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10615  enumInfo->m_name = enumName;
10616  enumInfo->m_values.reserve( values.size() );
10617 
10618  const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10619  assert( valueNames.size() == values.size() );
10620  std::size_t i = 0;
10621  for( auto value : values )
10622  enumInfo->m_values.emplace_back(value, valueNames[i++]);
10623 
10624  return enumInfo;
10625  }
10626 
10627  EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10628  m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10629  return *m_enumInfos.back();
10630  }
10631 
10632  } // Detail
10633 } // Catch
10634 
10635 // end catch_enum_values_registry.cpp
10636 // start catch_errno_guard.cpp
10637 
10638 #include <cerrno>
10639 
10640 namespace Catch {
10641  ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10642  ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10643 }
10644 // end catch_errno_guard.cpp
10645 // start catch_exception_translator_registry.cpp
10646 
10647 // start catch_exception_translator_registry.h
10648 
10649 #include <vector>
10650 #include <string>
10651 #include <memory>
10652 
10653 namespace Catch {
10654 
10655  class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10656  public:
10657  ~ExceptionTranslatorRegistry();
10658  virtual void registerTranslator( const IExceptionTranslator* translator );
10659  std::string translateActiveException() const override;
10660  std::string tryTranslators() const;
10661 
10662  private:
10663  std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10664  };
10665 }
10666 
10667 // end catch_exception_translator_registry.h
10668 #ifdef __OBJC__
10669 #import "Foundation/Foundation.h"
10670 #endif
10671 
10672 namespace Catch {
10673 
10674  ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10675  }
10676 
10677  void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10678  m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10679  }
10680 
10681 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10682  std::string ExceptionTranslatorRegistry::translateActiveException() const {
10683  try {
10684 #ifdef __OBJC__
10685  // In Objective-C try objective-c exceptions first
10686  @try {
10687  return tryTranslators();
10688  }
10689  @catch (NSException *exception) {
10690  return Catch::Detail::stringify( [exception description] );
10691  }
10692 #else
10693  // Compiling a mixed mode project with MSVC means that CLR
10694  // exceptions will be caught in (...) as well. However, these
10695  // do not fill-in std::current_exception and thus lead to crash
10696  // when attempting rethrow.
10697  // /EHa switch also causes structured exceptions to be caught
10698  // here, but they fill-in current_exception properly, so
10699  // at worst the output should be a little weird, instead of
10700  // causing a crash.
10701  if (std::current_exception() == nullptr) {
10702  return "Non C++ exception. Possibly a CLR exception.";
10703  }
10704  return tryTranslators();
10705 #endif
10706  }
10707  catch( TestFailureException& ) {
10708  std::rethrow_exception(std::current_exception());
10709  }
10710  catch( std::exception& ex ) {
10711  return ex.what();
10712  }
10713  catch( std::string& msg ) {
10714  return msg;
10715  }
10716  catch( const char* msg ) {
10717  return msg;
10718  }
10719  catch(...) {
10720  return "Unknown exception";
10721  }
10722  }
10723 
10724  std::string ExceptionTranslatorRegistry::tryTranslators() const {
10725  if (m_translators.empty()) {
10726  std::rethrow_exception(std::current_exception());
10727  } else {
10728  return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10729  }
10730  }
10731 
10732 #else // ^^ Exceptions are enabled // Exceptions are disabled vv
10733  std::string ExceptionTranslatorRegistry::translateActiveException() const {
10734  CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10735  }
10736 
10737  std::string ExceptionTranslatorRegistry::tryTranslators() const {
10738  CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10739  }
10740 #endif
10741 
10742 }
10743 // end catch_exception_translator_registry.cpp
10744 // start catch_fatal_condition.cpp
10745 
10746 #include <algorithm>
10747 
10748 #if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10749 
10750 namespace Catch {
10751 
10752  // If neither SEH nor signal handling is required, the handler impls
10753  // do not have to do anything, and can be empty.
10754  void FatalConditionHandler::engage_platform() {}
10755  void FatalConditionHandler::disengage_platform() {}
10756  FatalConditionHandler::FatalConditionHandler() = default;
10757  FatalConditionHandler::~FatalConditionHandler() = default;
10758 
10759 } // end namespace Catch
10760 
10761 #endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10762 
10763 #if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10764 #error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10765 #endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10766 
10767 #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10768 
10769 namespace {
10771  void reportFatal( char const * const message ) {
10772  Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10773  }
10774 
10778  constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10779 } // end unnamed namespace
10780 
10781 #endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10782 
10783 #if defined( CATCH_CONFIG_WINDOWS_SEH )
10784 
10785 namespace Catch {
10786 
10787  struct SignalDefs { DWORD id; const char* name; };
10788 
10789  // There is no 1-1 mapping between signals and windows exceptions.
10790  // Windows can easily distinguish between SO and SigSegV,
10791  // but SigInt, SigTerm, etc are handled differently.
10792  static SignalDefs signalDefs[] = {
10793  { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
10794  { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10795  { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10796  { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10797  };
10798 
10799  static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10800  for (auto const& def : signalDefs) {
10801  if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10802  reportFatal(def.name);
10803  }
10804  }
10805  // If its not an exception we care about, pass it along.
10806  // This stops us from eating debugger breaks etc.
10807  return EXCEPTION_CONTINUE_SEARCH;
10808  }
10809 
10810  // Since we do not support multiple instantiations, we put these
10811  // into global variables and rely on cleaning them up in outlined
10812  // constructors/destructors
10813  static PVOID exceptionHandlerHandle = nullptr;
10814 
10815  // For MSVC, we reserve part of the stack memory for handling
10816  // memory overflow structured exception.
10817  FatalConditionHandler::FatalConditionHandler() {
10818  ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
10819  if (!SetThreadStackGuarantee(&guaranteeSize)) {
10820  // We do not want to fully error out, because needing
10821  // the stack reserve should be rare enough anyway.
10822  Catch::cerr()
10823  << "Failed to reserve piece of stack."
10824  << " Stack overflows will not be reported successfully.";
10825  }
10826  }
10827 
10828  // We do not attempt to unset the stack guarantee, because
10829  // Windows does not support lowering the stack size guarantee.
10830  FatalConditionHandler::~FatalConditionHandler() = default;
10831 
10832  void FatalConditionHandler::engage_platform() {
10833  // Register as first handler in current chain
10834  exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10835  if (!exceptionHandlerHandle) {
10836  CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
10837  }
10838  }
10839 
10840  void FatalConditionHandler::disengage_platform() {
10841  if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10842  CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
10843  }
10844  exceptionHandlerHandle = nullptr;
10845  }
10846 
10847 } // end namespace Catch
10848 
10849 #endif // CATCH_CONFIG_WINDOWS_SEH
10850 
10851 #if defined( CATCH_CONFIG_POSIX_SIGNALS )
10852 
10853 #include <signal.h>
10854 
10855 namespace Catch {
10856 
10857  struct SignalDefs {
10858  int id;
10859  const char* name;
10860  };
10861 
10862  static SignalDefs signalDefs[] = {
10863  { SIGINT, "SIGINT - Terminal interrupt signal" },
10864  { SIGILL, "SIGILL - Illegal instruction signal" },
10865  { SIGFPE, "SIGFPE - Floating point error signal" },
10866  { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10867  { SIGTERM, "SIGTERM - Termination request signal" },
10868  { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10869  };
10870 
10871 // Older GCCs trigger -Wmissing-field-initializers for T foo = {}
10872 // which is zero initialization, but not explicit. We want to avoid
10873 // that.
10874 #if defined(__GNUC__)
10875 # pragma GCC diagnostic push
10876 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10877 #endif
10878 
10879  static char* altStackMem = nullptr;
10880  static std::size_t altStackSize = 0;
10881  static stack_t oldSigStack{};
10882  static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10883 
10884  static void restorePreviousSignalHandlers() {
10885  // We set signal handlers back to the previous ones. Hopefully
10886  // nobody overwrote them in the meantime, and doesn't expect
10887  // their signal handlers to live past ours given that they
10888  // installed them after ours..
10889  for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
10890  sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10891  }
10892  // Return the old stack
10893  sigaltstack(&oldSigStack, nullptr);
10894  }
10895 
10896  static void handleSignal( int sig ) {
10897  char const * name = "<unknown signal>";
10898  for (auto const& def : signalDefs) {
10899  if (sig == def.id) {
10900  name = def.name;
10901  break;
10902  }
10903  }
10904  // We need to restore previous signal handlers and let them do
10905  // their thing, so that the users can have the debugger break
10906  // when a signal is raised, and so on.
10907  restorePreviousSignalHandlers();
10908  reportFatal( name );
10909  raise( sig );
10910  }
10911 
10912  FatalConditionHandler::FatalConditionHandler() {
10913  assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
10914  if (altStackSize == 0) {
10915  altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10916  }
10917  altStackMem = new char[altStackSize]();
10918  }
10919 
10920  FatalConditionHandler::~FatalConditionHandler() {
10921  delete[] altStackMem;
10922  // We signal that another instance can be constructed by zeroing
10923  // out the pointer.
10924  altStackMem = nullptr;
10925  }
10926 
10927  void FatalConditionHandler::engage_platform() {
10928  stack_t sigStack;
10929  sigStack.ss_sp = altStackMem;
10930  sigStack.ss_size = altStackSize;
10931  sigStack.ss_flags = 0;
10932  sigaltstack(&sigStack, &oldSigStack);
10933  struct sigaction sa = { };
10934 
10935  sa.sa_handler = handleSignal;
10936  sa.sa_flags = SA_ONSTACK;
10937  for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10938  sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10939  }
10940  }
10941 
10942 #if defined(__GNUC__)
10943 # pragma GCC diagnostic pop
10944 #endif
10945 
10946  void FatalConditionHandler::disengage_platform() {
10947  restorePreviousSignalHandlers();
10948  }
10949 
10950 } // end namespace Catch
10951 
10952 #endif // CATCH_CONFIG_POSIX_SIGNALS
10953 // end catch_fatal_condition.cpp
10954 // start catch_generators.cpp
10955 
10956 #include <limits>
10957 #include <set>
10958 
10959 namespace Catch {
10960 
10961 IGeneratorTracker::~IGeneratorTracker() {}
10962 
10963 const char* GeneratorException::what() const noexcept {
10964  return m_msg;
10965 }
10966 
10967 namespace Generators {
10968 
10969  GeneratorUntypedBase::~GeneratorUntypedBase() {}
10970 
10971  auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10972  return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10973  }
10974 
10975 } // namespace Generators
10976 } // namespace Catch
10977 // end catch_generators.cpp
10978 // start catch_interfaces_capture.cpp
10979 
10980 namespace Catch {
10981  IResultCapture::~IResultCapture() = default;
10982 }
10983 // end catch_interfaces_capture.cpp
10984 // start catch_interfaces_config.cpp
10985 
10986 namespace Catch {
10987  IConfig::~IConfig() = default;
10988 }
10989 // end catch_interfaces_config.cpp
10990 // start catch_interfaces_exception.cpp
10991 
10992 namespace Catch {
10993  IExceptionTranslator::~IExceptionTranslator() = default;
10994  IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
10995 }
10996 // end catch_interfaces_exception.cpp
10997 // start catch_interfaces_registry_hub.cpp
10998 
10999 namespace Catch {
11000  IRegistryHub::~IRegistryHub() = default;
11001  IMutableRegistryHub::~IMutableRegistryHub() = default;
11002 }
11003 // end catch_interfaces_registry_hub.cpp
11004 // start catch_interfaces_reporter.cpp
11005 
11006 // start catch_reporter_listening.h
11007 
11008 namespace Catch {
11009 
11010  class ListeningReporter : public IStreamingReporter {
11011  using Reporters = std::vector<IStreamingReporterPtr>;
11012  Reporters m_listeners;
11013  IStreamingReporterPtr m_reporter = nullptr;
11014  ReporterPreferences m_preferences;
11015 
11016  public:
11017  ListeningReporter();
11018 
11019  void addListener( IStreamingReporterPtr&& listener );
11020  void addReporter( IStreamingReporterPtr&& reporter );
11021 
11022  public: // IStreamingReporter
11023 
11024  ReporterPreferences getPreferences() const override;
11025 
11026  void noMatchingTestCases( std::string const& spec ) override;
11027 
11028  void reportInvalidArguments(std::string const&arg) override;
11029 
11030  static std::set<Verbosity> getSupportedVerbosities();
11031 
11032 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11033  void benchmarkPreparing(std::string const& name) override;
11034  void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11035  void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11036  void benchmarkFailed(std::string const&) override;
11037 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11038 
11039  void testRunStarting( TestRunInfo const& testRunInfo ) override;
11040  void testGroupStarting( GroupInfo const& groupInfo ) override;
11041  void testCaseStarting( TestCaseInfo const& testInfo ) override;
11042  void sectionStarting( SectionInfo const& sectionInfo ) override;
11043  void assertionStarting( AssertionInfo const& assertionInfo ) override;
11044 
11045  // The return value indicates if the messages buffer should be cleared:
11046  bool assertionEnded( AssertionStats const& assertionStats ) override;
11047  void sectionEnded( SectionStats const& sectionStats ) override;
11048  void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11049  void testGroupEnded( TestGroupStats const& testGroupStats ) override;
11050  void testRunEnded( TestRunStats const& testRunStats ) override;
11051 
11052  void skipTest( TestCaseInfo const& testInfo ) override;
11053  bool isMulti() const override;
11054 
11055  };
11056 
11057 } // end namespace Catch
11058 
11059 // end catch_reporter_listening.h
11060 namespace Catch {
11061 
11062  ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
11063  : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11064 
11065  ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
11066  : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11067 
11068  std::ostream& ReporterConfig::stream() const { return *m_stream; }
11069  IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11070 
11071  TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
11072 
11073  GroupInfo::GroupInfo( std::string const& _name,
11074  std::size_t _groupIndex,
11075  std::size_t _groupsCount )
11076  : name( _name ),
11077  groupIndex( _groupIndex ),
11078  groupsCounts( _groupsCount )
11079  {}
11080 
11081  AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
11082  std::vector<MessageInfo> const& _infoMessages,
11083  Totals const& _totals )
11084  : assertionResult( _assertionResult ),
11085  infoMessages( _infoMessages ),
11086  totals( _totals )
11087  {
11088  assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11089 
11090  if( assertionResult.hasMessage() ) {
11091  // Copy message into messages list.
11092  // !TBD This should have been done earlier, somewhere
11093  MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11094  builder << assertionResult.getMessage();
11095  builder.m_info.message = builder.m_stream.str();
11096 
11097  infoMessages.push_back( builder.m_info );
11098  }
11099  }
11100 
11101  AssertionStats::~AssertionStats() = default;
11102 
11103  SectionStats::SectionStats( SectionInfo const& _sectionInfo,
11104  Counts const& _assertions,
11105  double _durationInSeconds,
11106  bool _missingAssertions )
11107  : sectionInfo( _sectionInfo ),
11108  assertions( _assertions ),
11109  durationInSeconds( _durationInSeconds ),
11110  missingAssertions( _missingAssertions )
11111  {}
11112 
11113  SectionStats::~SectionStats() = default;
11114 
11115  TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
11116  Totals const& _totals,
11117  std::string const& _stdOut,
11118  std::string const& _stdErr,
11119  bool _aborting )
11120  : testInfo( _testInfo ),
11121  totals( _totals ),
11122  stdOut( _stdOut ),
11123  stdErr( _stdErr ),
11124  aborting( _aborting )
11125  {}
11126 
11127  TestCaseStats::~TestCaseStats() = default;
11128 
11129  TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
11130  Totals const& _totals,
11131  bool _aborting )
11132  : groupInfo( _groupInfo ),
11133  totals( _totals ),
11134  aborting( _aborting )
11135  {}
11136 
11137  TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
11138  : groupInfo( _groupInfo ),
11139  aborting( false )
11140  {}
11141 
11142  TestGroupStats::~TestGroupStats() = default;
11143 
11144  TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
11145  Totals const& _totals,
11146  bool _aborting )
11147  : runInfo( _runInfo ),
11148  totals( _totals ),
11149  aborting( _aborting )
11150  {}
11151 
11152  TestRunStats::~TestRunStats() = default;
11153 
11154  void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11155  bool IStreamingReporter::isMulti() const { return false; }
11156 
11157  IReporterFactory::~IReporterFactory() = default;
11158  IReporterRegistry::~IReporterRegistry() = default;
11159 
11160 } // end namespace Catch
11161 // end catch_interfaces_reporter.cpp
11162 // start catch_interfaces_runner.cpp
11163 
11164 namespace Catch {
11165  IRunner::~IRunner() = default;
11166 }
11167 // end catch_interfaces_runner.cpp
11168 // start catch_interfaces_testcase.cpp
11169 
11170 namespace Catch {
11171  ITestInvoker::~ITestInvoker() = default;
11172  ITestCaseRegistry::~ITestCaseRegistry() = default;
11173 }
11174 // end catch_interfaces_testcase.cpp
11175 // start catch_leak_detector.cpp
11176 
11177 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11178 #include <crtdbg.h>
11179 
11180 namespace Catch {
11181 
11182  LeakDetector::LeakDetector() {
11183  int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11184  flag |= _CRTDBG_LEAK_CHECK_DF;
11185  flag |= _CRTDBG_ALLOC_MEM_DF;
11186  _CrtSetDbgFlag(flag);
11187  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11188  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11189  // Change this to leaking allocation's number to break there
11190  _CrtSetBreakAlloc(-1);
11191  }
11192 }
11193 
11194 #else
11195 
11196  Catch::LeakDetector::LeakDetector() {}
11197 
11198 #endif
11199 
11200 Catch::LeakDetector::~LeakDetector() {
11201  Catch::cleanUp();
11202 }
11203 // end catch_leak_detector.cpp
11204 // start catch_list.cpp
11205 
11206 // start catch_list.h
11207 
11208 #include <set>
11209 
11210 namespace Catch {
11211 
11212  std::size_t listTests( Config const& config );
11213 
11214  std::size_t listTestsNamesOnly( Config const& config );
11215 
11216  struct TagInfo {
11217  void add( std::string const& spelling );
11218  std::string all() const;
11219 
11220  std::set<std::string> spellings;
11221  std::size_t count = 0;
11222  };
11223 
11224  std::size_t listTags( Config const& config );
11225 
11226  std::size_t listReporters();
11227 
11228  Option<std::size_t> list( std::shared_ptr<Config> const& config );
11229 
11230 } // end namespace Catch
11231 
11232 // end catch_list.h
11233 // start catch_text.h
11234 
11235 namespace Catch {
11236  using namespace clara::TextFlow;
11237 }
11238 
11239 // end catch_text.h
11240 #include <limits>
11241 #include <algorithm>
11242 #include <iomanip>
11243 
11244 namespace Catch {
11245 
11246  std::size_t listTests( Config const& config ) {
11247  TestSpec const& testSpec = config.testSpec();
11248  if( config.hasTestFilters() )
11249  Catch::cout() << "Matching test cases:\n";
11250  else {
11251  Catch::cout() << "All available test cases:\n";
11252  }
11253 
11254  auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11255  for( auto const& testCaseInfo : matchedTestCases ) {
11256  Colour::Code colour = testCaseInfo.isHidden()
11257  ? Colour::SecondaryText
11258  : Colour::None;
11259  Colour colourGuard( colour );
11260 
11261  Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
11262  if( config.verbosity() >= Verbosity::High ) {
11263  Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11264  std::string description = testCaseInfo.description;
11265  if( description.empty() )
11266  description = "(NO DESCRIPTION)";
11267  Catch::cout() << Column( description ).indent(4) << std::endl;
11268  }
11269  if( !testCaseInfo.tags.empty() )
11270  Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
11271  }
11272 
11273  if( !config.hasTestFilters() )
11274  Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
11275  else
11276  Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
11277  return matchedTestCases.size();
11278  }
11279 
11280  std::size_t listTestsNamesOnly( Config const& config ) {
11281  TestSpec const& testSpec = config.testSpec();
11282  std::size_t matchedTests = 0;
11283  std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11284  for( auto const& testCaseInfo : matchedTestCases ) {
11285  matchedTests++;
11286  if( startsWith( testCaseInfo.name, '#' ) )
11287  Catch::cout() << '"' << testCaseInfo.name << '"';
11288  else
11289  Catch::cout() << testCaseInfo.name;
11290  if ( config.verbosity() >= Verbosity::High )
11291  Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11292  Catch::cout() << std::endl;
11293  }
11294  return matchedTests;
11295  }
11296 
11297  void TagInfo::add( std::string const& spelling ) {
11298  ++count;
11299  spellings.insert( spelling );
11300  }
11301 
11302  std::string TagInfo::all() const {
11303  size_t size = 0;
11304  for (auto const& spelling : spellings) {
11305  // Add 2 for the brackes
11306  size += spelling.size() + 2;
11307  }
11308 
11309  std::string out; out.reserve(size);
11310  for (auto const& spelling : spellings) {
11311  out += '[';
11312  out += spelling;
11313  out += ']';
11314  }
11315  return out;
11316  }
11317 
11318  std::size_t listTags( Config const& config ) {
11319  TestSpec const& testSpec = config.testSpec();
11320  if( config.hasTestFilters() )
11321  Catch::cout() << "Tags for matching test cases:\n";
11322  else {
11323  Catch::cout() << "All available tags:\n";
11324  }
11325 
11326  std::map<std::string, TagInfo> tagCounts;
11327 
11328  std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11329  for( auto const& testCase : matchedTestCases ) {
11330  for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
11331  std::string lcaseTagName = toLower( tagName );
11332  auto countIt = tagCounts.find( lcaseTagName );
11333  if( countIt == tagCounts.end() )
11334  countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11335  countIt->second.add( tagName );
11336  }
11337  }
11338 
11339  for( auto const& tagCount : tagCounts ) {
11341  rss << " " << std::setw(2) << tagCount.second.count << " ";
11342  auto str = rss.str();
11343  auto wrapper = Column( tagCount.second.all() )
11344  .initialIndent( 0 )
11345  .indent( str.size() )
11346  .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11347  Catch::cout() << str << wrapper << '\n';
11348  }
11349  Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
11350  return tagCounts.size();
11351  }
11352 
11353  std::size_t listReporters() {
11354  Catch::cout() << "Available reporters:\n";
11355  IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
11356  std::size_t maxNameLen = 0;
11357  for( auto const& factoryKvp : factories )
11358  maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11359 
11360  for( auto const& factoryKvp : factories ) {
11361  Catch::cout()
11362  << Column( factoryKvp.first + ":" )
11363  .indent(2)
11364  .width( 5+maxNameLen )
11365  + Column( factoryKvp.second->getDescription() )
11366  .initialIndent(0)
11367  .indent(2)
11368  .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11369  << "\n";
11370  }
11371  Catch::cout() << std::endl;
11372  return factories.size();
11373  }
11374 
11375  Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
11376  Option<std::size_t> listedCount;
11377  getCurrentMutableContext().setConfig( config );
11378  if( config->listTests() )
11379  listedCount = listedCount.valueOr(0) + listTests( *config );
11380  if( config->listTestNamesOnly() )
11381  listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11382  if( config->listTags() )
11383  listedCount = listedCount.valueOr(0) + listTags( *config );
11384  if( config->listReporters() )
11385  listedCount = listedCount.valueOr(0) + listReporters();
11386  return listedCount;
11387  }
11388 
11389 } // end namespace Catch
11390 // end catch_list.cpp
11391 // start catch_matchers.cpp
11392 
11393 namespace Catch {
11394 namespace Matchers {
11395  namespace Impl {
11396 
11397  std::string MatcherUntypedBase::toString() const {
11398  if( m_cachedToString.empty() )
11399  m_cachedToString = describe();
11400  return m_cachedToString;
11401  }
11402 
11403  MatcherUntypedBase::~MatcherUntypedBase() = default;
11404 
11405  } // namespace Impl
11406 } // namespace Matchers
11407 
11408 using namespace Matchers;
11410 
11411 } // namespace Catch
11412 // end catch_matchers.cpp
11413 // start catch_matchers_exception.cpp
11414 
11415 namespace Catch {
11416 namespace Matchers {
11417 namespace Exception {
11418 
11419 bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11420  return ex.what() == m_message;
11421 }
11422 
11423 std::string ExceptionMessageMatcher::describe() const {
11424  return "exception message matches \"" + m_message + "\"";
11425 }
11426 
11427 }
11428 Exception::ExceptionMessageMatcher Message(std::string const& message) {
11429  return Exception::ExceptionMessageMatcher(message);
11430 }
11431 
11432 // namespace Exception
11433 } // namespace Matchers
11434 } // namespace Catch
11435 // end catch_matchers_exception.cpp
11436 // start catch_matchers_floating.cpp
11437 
11438 // start catch_polyfills.hpp
11439 
11440 namespace Catch {
11441  bool isnan(float f);
11442  bool isnan(double d);
11443 }
11444 
11445 // end catch_polyfills.hpp
11446 // start catch_to_string.hpp
11447 
11448 #include <string>
11449 
11450 namespace Catch {
11451  template <typename T>
11452  std::string to_string(T const& t) {
11453 #if defined(CATCH_CONFIG_CPP11_TO_STRING)
11454  return std::to_string(t);
11455 #else
11457  rss << t;
11458  return rss.str();
11459 #endif
11460  }
11461 } // end namespace Catch
11462 
11463 // end catch_to_string.hpp
11464 #include <algorithm>
11465 #include <cmath>
11466 #include <cstdlib>
11467 #include <cstdint>
11468 #include <cstring>
11469 #include <sstream>
11470 #include <type_traits>
11471 #include <iomanip>
11472 #include <limits>
11473 
11474 namespace Catch {
11475 namespace {
11476 
11477  int32_t convert(float f) {
11478  static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11479  int32_t i;
11480  std::memcpy(&i, &f, sizeof(f));
11481  return i;
11482  }
11483 
11484  int64_t convert(double d) {
11485  static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11486  int64_t i;
11487  std::memcpy(&i, &d, sizeof(d));
11488  return i;
11489  }
11490 
11491  template <typename FP>
11492  bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11493  // Comparison with NaN should always be false.
11494  // This way we can rule it out before getting into the ugly details
11495  if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11496  return false;
11497  }
11498 
11499  auto lc = convert(lhs);
11500  auto rc = convert(rhs);
11501 
11502  if ((lc < 0) != (rc < 0)) {
11503  // Potentially we can have +0 and -0
11504  return lhs == rhs;
11505  }
11506 
11507  // static cast as a workaround for IBM XLC
11508  auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11509  return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11510  }
11511 
11512 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11513 
11514  float nextafter(float x, float y) {
11515  return ::nextafterf(x, y);
11516  }
11517 
11518  double nextafter(double x, double y) {
11519  return ::nextafter(x, y);
11520  }
11521 
11522 #endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11523 
11524 template <typename FP>
11525 FP step(FP start, FP direction, uint64_t steps) {
11526  for (uint64_t i = 0; i < steps; ++i) {
11527 #if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11528  start = Catch::nextafter(start, direction);
11529 #else
11530  start = std::nextafter(start, direction);
11531 #endif
11532  }
11533  return start;
11534 }
11535 
11536 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11537 // But without the subtraction to allow for INFINITY in comparison
11538 bool marginComparison(double lhs, double rhs, double margin) {
11539  return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11540 }
11541 
11542 template <typename FloatingPoint>
11543 void write(std::ostream& out, FloatingPoint num) {
11544  out << std::scientific
11545  << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11546  << num;
11547 }
11548 
11549 } // end anonymous namespace
11550 
11551 namespace Matchers {
11552 namespace Floating {
11553 
11554  enum class FloatingPointKind : uint8_t {
11555  Float,
11556  Double
11557  };
11558 
11559  WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11560  :m_target{ target }, m_margin{ margin } {
11561  CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11562  << " Margin has to be non-negative.");
11563  }
11564 
11565  // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11566  // But without the subtraction to allow for INFINITY in comparison
11567  bool WithinAbsMatcher::match(double const& matchee) const {
11568  return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11569  }
11570 
11571  std::string WithinAbsMatcher::describe() const {
11572  return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11573  }
11574 
11575  WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11576  :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11577  CATCH_ENFORCE(m_type == FloatingPointKind::Double
11578  || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11579  "Provided ULP is impossibly large for a float comparison.");
11580  }
11581 
11582 #if defined(__clang__)
11583 #pragma clang diagnostic push
11584 // Clang <3.5 reports on the default branch in the switch below
11585 #pragma clang diagnostic ignored "-Wunreachable-code"
11586 #endif
11587 
11588  bool WithinUlpsMatcher::match(double const& matchee) const {
11589  switch (m_type) {
11590  case FloatingPointKind::Float:
11591  return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11592  case FloatingPointKind::Double:
11593  return almostEqualUlps<double>(matchee, m_target, m_ulps);
11594  default:
11595  CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11596  }
11597  }
11598 
11599 #if defined(__clang__)
11600 #pragma clang diagnostic pop
11601 #endif
11602 
11603  std::string WithinUlpsMatcher::describe() const {
11604  std::stringstream ret;
11605 
11606  ret << "is within " << m_ulps << " ULPs of ";
11607 
11608  if (m_type == FloatingPointKind::Float) {
11609  write(ret, static_cast<float>(m_target));
11610  ret << 'f';
11611  } else {
11612  write(ret, m_target);
11613  }
11614 
11615  ret << " ([";
11616  if (m_type == FloatingPointKind::Double) {
11617  write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11618  ret << ", ";
11619  write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11620  } else {
11621  // We have to cast INFINITY to float because of MinGW, see #1782
11622  write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11623  ret << ", ";
11624  write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11625  }
11626  ret << "])";
11627 
11628  return ret.str();
11629  }
11630 
11631  WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
11632  m_target(target),
11633  m_epsilon(epsilon){
11634  CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
11635  CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11636  }
11637 
11638  bool WithinRelMatcher::match(double const& matchee) const {
11639  const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11640  return marginComparison(matchee, m_target,
11641  std::isinf(relMargin)? 0 : relMargin);
11642  }
11643 
11644  std::string WithinRelMatcher::describe() const {
11645  Catch::ReusableStringStream sstr;
11646  sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11647  return sstr.str();
11648  }
11649 
11650 }// namespace Floating
11651 
11652 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11653  return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11654 }
11655 
11656 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11657  return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11658 }
11659 
11660 Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11661  return Floating::WithinAbsMatcher(target, margin);
11662 }
11663 
11664 Floating::WithinRelMatcher WithinRel(double target, double eps) {
11665  return Floating::WithinRelMatcher(target, eps);
11666 }
11667 
11668 Floating::WithinRelMatcher WithinRel(double target) {
11669  return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11670 }
11671 
11672 Floating::WithinRelMatcher WithinRel(float target, float eps) {
11673  return Floating::WithinRelMatcher(target, eps);
11674 }
11675 
11676 Floating::WithinRelMatcher WithinRel(float target) {
11677  return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11678 }
11679 
11680 } // namespace Matchers
11681 } // namespace Catch
11682 // end catch_matchers_floating.cpp
11683 // start catch_matchers_generic.cpp
11684 
11685 std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11686  if (desc.empty()) {
11687  return "matches undescribed predicate";
11688  } else {
11689  return "matches predicate: \"" + desc + '"';
11690  }
11691 }
11692 // end catch_matchers_generic.cpp
11693 // start catch_matchers_string.cpp
11694 
11695 #include <regex>
11696 
11697 namespace Catch {
11698 namespace Matchers {
11699 
11700  namespace StdString {
11701 
11702  CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11703  : m_caseSensitivity( caseSensitivity ),
11704  m_str( adjustString( str ) )
11705  {}
11706  std::string CasedString::adjustString( std::string const& str ) const {
11707  return m_caseSensitivity == CaseSensitive::No
11708  ? toLower( str )
11709  : str;
11710  }
11711  std::string CasedString::caseSensitivitySuffix() const {
11712  return m_caseSensitivity == CaseSensitive::No
11713  ? " (case insensitive)"
11714  : std::string();
11715  }
11716 
11717  StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11718  : m_comparator( comparator ),
11719  m_operation( operation ) {
11720  }
11721 
11722  std::string StringMatcherBase::describe() const {
11723  std::string description;
11724  description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11725  m_comparator.caseSensitivitySuffix().size());
11726  description += m_operation;
11727  description += ": \"";
11728  description += m_comparator.m_str;
11729  description += "\"";
11730  description += m_comparator.caseSensitivitySuffix();
11731  return description;
11732  }
11733 
11734  EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11735 
11736  bool EqualsMatcher::match( std::string const& source ) const {
11737  return m_comparator.adjustString( source ) == m_comparator.m_str;
11738  }
11739 
11740  ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11741 
11742  bool ContainsMatcher::match( std::string const& source ) const {
11743  return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11744  }
11745 
11746  StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11747 
11748  bool StartsWithMatcher::match( std::string const& source ) const {
11749  return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11750  }
11751 
11752  EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11753 
11754  bool EndsWithMatcher::match( std::string const& source ) const {
11755  return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11756  }
11757 
11758  RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11759 
11760  bool RegexMatcher::match(std::string const& matchee) const {
11761  auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11762  if (m_caseSensitivity == CaseSensitive::Choice::No) {
11763  flags |= std::regex::icase;
11764  }
11765  auto reg = std::regex(m_regex, flags);
11766  return std::regex_match(matchee, reg);
11767  }
11768 
11769  std::string RegexMatcher::describe() const {
11770  return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11771  }
11772 
11773  } // namespace StdString
11774 
11775  StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11776  return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11777  }
11778  StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11779  return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11780  }
11781  StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11782  return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11783  }
11784  StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11785  return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11786  }
11787 
11788  StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11789  return StdString::RegexMatcher(regex, caseSensitivity);
11790  }
11791 
11792 } // namespace Matchers
11793 } // namespace Catch
11794 // end catch_matchers_string.cpp
11795 // start catch_message.cpp
11796 
11797 // start catch_uncaught_exceptions.h
11798 
11799 namespace Catch {
11800  bool uncaught_exceptions();
11801 } // end namespace Catch
11802 
11803 // end catch_uncaught_exceptions.h
11804 #include <cassert>
11805 #include <stack>
11806 
11807 namespace Catch {
11808 
11809  MessageInfo::MessageInfo( StringRef const& _macroName,
11810  SourceLineInfo const& _lineInfo,
11811  ResultWas::OfType _type )
11812  : macroName( _macroName ),
11813  lineInfo( _lineInfo ),
11814  type( _type ),
11815  sequence( ++globalCount )
11816  {}
11817 
11818  bool MessageInfo::operator==( MessageInfo const& other ) const {
11819  return sequence == other.sequence;
11820  }
11821 
11822  bool MessageInfo::operator<( MessageInfo const& other ) const {
11823  return sequence < other.sequence;
11824  }
11825 
11826  // This may need protecting if threading support is added
11827  unsigned int MessageInfo::globalCount = 0;
11828 
11830 
11831  Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11832  SourceLineInfo const& lineInfo,
11833  ResultWas::OfType type )
11834  :m_info(macroName, lineInfo, type) {}
11835 
11837 
11838  ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11839  : m_info( builder.m_info ), m_moved()
11840  {
11841  m_info.message = builder.m_stream.str();
11842  getResultCapture().pushScopedMessage( m_info );
11843  }
11844 
11845  ScopedMessage::ScopedMessage( ScopedMessage&& old )
11846  : m_info( old.m_info ), m_moved()
11847  {
11848  old.m_moved = true;
11849  }
11850 
11851  ScopedMessage::~ScopedMessage() {
11852  if ( !uncaught_exceptions() && !m_moved ){
11853  getResultCapture().popScopedMessage(m_info);
11854  }
11855  }
11856 
11857  Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11858  auto trimmed = [&] (size_t start, size_t end) {
11859  while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11860  ++start;
11861  }
11862  while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11863  --end;
11864  }
11865  return names.substr(start, end - start + 1);
11866  };
11867  auto skipq = [&] (size_t start, char quote) {
11868  for (auto i = start + 1; i < names.size() ; ++i) {
11869  if (names[i] == quote)
11870  return i;
11871  if (names[i] == '\\')
11872  ++i;
11873  }
11874  CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11875  };
11876 
11877  size_t start = 0;
11878  std::stack<char> openings;
11879  for (size_t pos = 0; pos < names.size(); ++pos) {
11880  char c = names[pos];
11881  switch (c) {
11882  case '[':
11883  case '{':
11884  case '(':
11885  // It is basically impossible to disambiguate between
11886  // comparison and start of template args in this context
11887 // case '<':
11888  openings.push(c);
11889  break;
11890  case ']':
11891  case '}':
11892  case ')':
11893 // case '>':
11894  openings.pop();
11895  break;
11896  case '"':
11897  case '\'':
11898  pos = skipq(pos, c);
11899  break;
11900  case ',':
11901  if (start != pos && openings.empty()) {
11902  m_messages.emplace_back(macroName, lineInfo, resultType);
11903  m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11904  m_messages.back().message += " := ";
11905  start = pos;
11906  }
11907  }
11908  }
11909  assert(openings.empty() && "Mismatched openings");
11910  m_messages.emplace_back(macroName, lineInfo, resultType);
11911  m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11912  m_messages.back().message += " := ";
11913  }
11914  Capturer::~Capturer() {
11915  if ( !uncaught_exceptions() ){
11916  assert( m_captured == m_messages.size() );
11917  for( size_t i = 0; i < m_captured; ++i )
11918  m_resultCapture.popScopedMessage( m_messages[i] );
11919  }
11920  }
11921 
11922  void Capturer::captureValue( size_t index, std::string const& value ) {
11923  assert( index < m_messages.size() );
11924  m_messages[index].message += value;
11925  m_resultCapture.pushScopedMessage( m_messages[index] );
11926  m_captured++;
11927  }
11928 
11929 } // end namespace Catch
11930 // end catch_message.cpp
11931 // start catch_output_redirect.cpp
11932 
11933 // start catch_output_redirect.h
11934 #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11935 #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11936 
11937 #include <cstdio>
11938 #include <iosfwd>
11939 #include <string>
11940 
11941 namespace Catch {
11942 
11943  class RedirectedStream {
11944  std::ostream& m_originalStream;
11945  std::ostream& m_redirectionStream;
11946  std::streambuf* m_prevBuf;
11947 
11948  public:
11949  RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11950  ~RedirectedStream();
11951  };
11952 
11953  class RedirectedStdOut {
11954  ReusableStringStream m_rss;
11955  RedirectedStream m_cout;
11956  public:
11957  RedirectedStdOut();
11958  auto str() const -> std::string;
11959  };
11960 
11961  // StdErr has two constituent streams in C++, std::cerr and std::clog
11962  // This means that we need to redirect 2 streams into 1 to keep proper
11963  // order of writes
11964  class RedirectedStdErr {
11965  ReusableStringStream m_rss;
11966  RedirectedStream m_cerr;
11967  RedirectedStream m_clog;
11968  public:
11969  RedirectedStdErr();
11970  auto str() const -> std::string;
11971  };
11972 
11973  class RedirectedStreams {
11974  public:
11975  RedirectedStreams(RedirectedStreams const&) = delete;
11976  RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11977  RedirectedStreams(RedirectedStreams&&) = delete;
11978  RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11979 
11980  RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11981  ~RedirectedStreams();
11982  private:
11983  std::string& m_redirectedCout;
11984  std::string& m_redirectedCerr;
11985  RedirectedStdOut m_redirectedStdOut;
11986  RedirectedStdErr m_redirectedStdErr;
11987  };
11988 
11989 #if defined(CATCH_CONFIG_NEW_CAPTURE)
11990 
11991  // Windows's implementation of std::tmpfile is terrible (it tries
11992  // to create a file inside system folder, thus requiring elevated
11993  // privileges for the binary), so we have to use tmpnam(_s) and
11994  // create the file ourselves there.
11995  class TempFile {
11996  public:
11997  TempFile(TempFile const&) = delete;
11998  TempFile& operator=(TempFile const&) = delete;
11999  TempFile(TempFile&&) = delete;
12000  TempFile& operator=(TempFile&&) = delete;
12001 
12002  TempFile();
12003  ~TempFile();
12004 
12005  std::FILE* getFile();
12006  std::string getContents();
12007 
12008  private:
12009  std::FILE* m_file = nullptr;
12010  #if defined(_MSC_VER)
12011  char m_buffer[L_tmpnam] = { 0 };
12012  #endif
12013  };
12014 
12015  class OutputRedirect {
12016  public:
12017  OutputRedirect(OutputRedirect const&) = delete;
12018  OutputRedirect& operator=(OutputRedirect const&) = delete;
12019  OutputRedirect(OutputRedirect&&) = delete;
12020  OutputRedirect& operator=(OutputRedirect&&) = delete;
12021 
12022  OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12023  ~OutputRedirect();
12024 
12025  private:
12026  int m_originalStdout = -1;
12027  int m_originalStderr = -1;
12028  TempFile m_stdoutFile;
12029  TempFile m_stderrFile;
12030  std::string& m_stdoutDest;
12031  std::string& m_stderrDest;
12032  };
12033 
12034 #endif
12035 
12036 } // end namespace Catch
12037 
12038 #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12039 // end catch_output_redirect.h
12040 #include <cstdio>
12041 #include <cstring>
12042 #include <fstream>
12043 #include <sstream>
12044 #include <stdexcept>
12045 
12046 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12047  #if defined(_MSC_VER)
12048  #include <io.h> //_dup and _dup2
12049  #define dup _dup
12050  #define dup2 _dup2
12051  #define fileno _fileno
12052  #else
12053  #include <unistd.h> // dup and dup2
12054  #endif
12055 #endif
12056 
12057 namespace Catch {
12058 
12059  RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12060  : m_originalStream( originalStream ),
12061  m_redirectionStream( redirectionStream ),
12062  m_prevBuf( m_originalStream.rdbuf() )
12063  {
12064  m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12065  }
12066 
12067  RedirectedStream::~RedirectedStream() {
12068  m_originalStream.rdbuf( m_prevBuf );
12069  }
12070 
12071  RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12072  auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12073 
12074  RedirectedStdErr::RedirectedStdErr()
12075  : m_cerr( Catch::cerr(), m_rss.get() ),
12076  m_clog( Catch::clog(), m_rss.get() )
12077  {}
12078  auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12079 
12080  RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12081  : m_redirectedCout(redirectedCout),
12082  m_redirectedCerr(redirectedCerr)
12083  {}
12084 
12085  RedirectedStreams::~RedirectedStreams() {
12086  m_redirectedCout += m_redirectedStdOut.str();
12087  m_redirectedCerr += m_redirectedStdErr.str();
12088  }
12089 
12090 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12091 
12092 #if defined(_MSC_VER)
12093  TempFile::TempFile() {
12094  if (tmpnam_s(m_buffer)) {
12095  CATCH_RUNTIME_ERROR("Could not get a temp filename");
12096  }
12097  if (fopen_s(&m_file, m_buffer, "w+")) {
12098  char buffer[100];
12099  if (strerror_s(buffer, errno)) {
12100  CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12101  }
12102  CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12103  }
12104  }
12105 #else
12106  TempFile::TempFile() {
12107  m_file = std::tmpfile();
12108  if (!m_file) {
12109  CATCH_RUNTIME_ERROR("Could not create a temp file.");
12110  }
12111  }
12112 
12113 #endif
12114 
12115  TempFile::~TempFile() {
12116  // TBD: What to do about errors here?
12117  std::fclose(m_file);
12118  // We manually create the file on Windows only, on Linux
12119  // it will be autodeleted
12120 #if defined(_MSC_VER)
12121  std::remove(m_buffer);
12122 #endif
12123  }
12124 
12125  FILE* TempFile::getFile() {
12126  return m_file;
12127  }
12128 
12129  std::string TempFile::getContents() {
12130  std::stringstream sstr;
12131  char buffer[100] = {};
12132  std::rewind(m_file);
12133  while (std::fgets(buffer, sizeof(buffer), m_file)) {
12134  sstr << buffer;
12135  }
12136  return sstr.str();
12137  }
12138 
12139  OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12140  m_originalStdout(dup(1)),
12141  m_originalStderr(dup(2)),
12142  m_stdoutDest(stdout_dest),
12143  m_stderrDest(stderr_dest) {
12144  dup2(fileno(m_stdoutFile.getFile()), 1);
12145  dup2(fileno(m_stderrFile.getFile()), 2);
12146  }
12147 
12148  OutputRedirect::~OutputRedirect() {
12149  Catch::cout() << std::flush;
12150  fflush(stdout);
12151  // Since we support overriding these streams, we flush cerr
12152  // even though std::cerr is unbuffered
12153  Catch::cerr() << std::flush;
12154  Catch::clog() << std::flush;
12155  fflush(stderr);
12156 
12157  dup2(m_originalStdout, 1);
12158  dup2(m_originalStderr, 2);
12159 
12160  m_stdoutDest += m_stdoutFile.getContents();
12161  m_stderrDest += m_stderrFile.getContents();
12162  }
12163 
12164 #endif // CATCH_CONFIG_NEW_CAPTURE
12165 
12166 } // namespace Catch
12167 
12168 #if defined(CATCH_CONFIG_NEW_CAPTURE)
12169  #if defined(_MSC_VER)
12170  #undef dup
12171  #undef dup2
12172  #undef fileno
12173  #endif
12174 #endif
12175 // end catch_output_redirect.cpp
12176 // start catch_polyfills.cpp
12177 
12178 #include <cmath>
12179 
12180 namespace Catch {
12181 
12182 #if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12183  bool isnan(float f) {
12184  return std::isnan(f);
12185  }
12186  bool isnan(double d) {
12187  return std::isnan(d);
12188  }
12189 #else
12190  // For now we only use this for embarcadero
12191  bool isnan(float f) {
12192  return std::_isnan(f);
12193  }
12194  bool isnan(double d) {
12195  return std::_isnan(d);
12196  }
12197 #endif
12198 
12199 } // end namespace Catch
12200 // end catch_polyfills.cpp
12201 // start catch_random_number_generator.cpp
12202 
12203 namespace Catch {
12204 
12205 namespace {
12206 
12207 #if defined(_MSC_VER)
12208 #pragma warning(push)
12209 #pragma warning(disable:4146) // we negate uint32 during the rotate
12210 #endif
12211  // Safe rotr implementation thanks to John Regehr
12212  uint32_t rotate_right(uint32_t val, uint32_t count) {
12213  const uint32_t mask = 31;
12214  count &= mask;
12215  return (val >> count) | (val << (-count & mask));
12216  }
12217 
12218 #if defined(_MSC_VER)
12219 #pragma warning(pop)
12220 #endif
12221 
12222 }
12223 
12224  SimplePcg32::SimplePcg32(result_type seed_) {
12225  seed(seed_);
12226  }
12227 
12228  void SimplePcg32::seed(result_type seed_) {
12229  m_state = 0;
12230  (*this)();
12231  m_state += seed_;
12232  (*this)();
12233  }
12234 
12235  void SimplePcg32::discard(uint64_t skip) {
12236  // We could implement this to run in O(log n) steps, but this
12237  // should suffice for our use case.
12238  for (uint64_t s = 0; s < skip; ++s) {
12239  static_cast<void>((*this)());
12240  }
12241  }
12242 
12243  SimplePcg32::result_type SimplePcg32::operator()() {
12244  // prepare the output value
12245  const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12246  const auto output = rotate_right(xorshifted, m_state >> 59u);
12247 
12248  // advance state
12249  m_state = m_state * 6364136223846793005ULL + s_inc;
12250 
12251  return output;
12252  }
12253 
12254  bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12255  return lhs.m_state == rhs.m_state;
12256  }
12257 
12258  bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12259  return lhs.m_state != rhs.m_state;
12260  }
12261 }
12262 // end catch_random_number_generator.cpp
12263 // start catch_registry_hub.cpp
12264 
12265 // start catch_test_case_registry_impl.h
12266 
12267 #include <vector>
12268 #include <set>
12269 #include <algorithm>
12270 #include <ios>
12271 
12272 namespace Catch {
12273 
12274  class TestCase;
12275  struct IConfig;
12276 
12277  std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
12278 
12279  bool isThrowSafe( TestCase const& testCase, IConfig const& config );
12280  bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
12281 
12282  void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
12283 
12284  std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
12285  std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
12286 
12287  class TestRegistry : public ITestCaseRegistry {
12288  public:
12289  virtual ~TestRegistry() = default;
12290 
12291  virtual void registerTest( TestCase const& testCase );
12292 
12293  std::vector<TestCase> const& getAllTests() const override;
12294  std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
12295 
12296  private:
12297  std::vector<TestCase> m_functions;
12298  mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12299  mutable std::vector<TestCase> m_sortedFunctions;
12300  std::size_t m_unnamedCount = 0;
12301  std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12302  };
12303 
12305 
12306  class TestInvokerAsFunction : public ITestInvoker {
12307  void(*m_testAsFunction)();
12308  public:
12309  TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
12310 
12311  void invoke() const override;
12312  };
12313 
12314  std::string extractClassName( StringRef const& classOrQualifiedMethodName );
12315 
12317 
12318 } // end namespace Catch
12319 
12320 // end catch_test_case_registry_impl.h
12321 // start catch_reporter_registry.h
12322 
12323 #include <map>
12324 
12325 namespace Catch {
12326 
12327  class ReporterRegistry : public IReporterRegistry {
12328 
12329  public:
12330 
12331  ~ReporterRegistry() override;
12332 
12333  IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
12334 
12335  void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
12336  void registerListener( IReporterFactoryPtr const& factory );
12337 
12338  FactoryMap const& getFactories() const override;
12339  Listeners const& getListeners() const override;
12340 
12341  private:
12342  FactoryMap m_factories;
12343  Listeners m_listeners;
12344  };
12345 }
12346 
12347 // end catch_reporter_registry.h
12348 // start catch_tag_alias_registry.h
12349 
12350 // start catch_tag_alias.h
12351 
12352 #include <string>
12353 
12354 namespace Catch {
12355 
12356  struct TagAlias {
12357  TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12358 
12359  std::string tag;
12360  SourceLineInfo lineInfo;
12361  };
12362 
12363 } // end namespace Catch
12364 
12365 // end catch_tag_alias.h
12366 #include <map>
12367 
12368 namespace Catch {
12369 
12370  class TagAliasRegistry : public ITagAliasRegistry {
12371  public:
12372  ~TagAliasRegistry() override;
12373  TagAlias const* find( std::string const& alias ) const override;
12374  std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
12375  void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
12376 
12377  private:
12378  std::map<std::string, TagAlias> m_registry;
12379  };
12380 
12381 } // end namespace Catch
12382 
12383 // end catch_tag_alias_registry.h
12384 // start catch_startup_exception_registry.h
12385 
12386 #include <vector>
12387 #include <exception>
12388 
12389 namespace Catch {
12390 
12391  class StartupExceptionRegistry {
12392 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12393  public:
12394  void add(std::exception_ptr const& exception) noexcept;
12395  std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12396  private:
12397  std::vector<std::exception_ptr> m_exceptions;
12398 #endif
12399  };
12400 
12401 } // end namespace Catch
12402 
12403 // end catch_startup_exception_registry.h
12404 // start catch_singletons.hpp
12405 
12406 namespace Catch {
12407 
12408  struct ISingleton {
12409  virtual ~ISingleton();
12410  };
12411 
12412  void addSingleton( ISingleton* singleton );
12413  void cleanupSingletons();
12414 
12415  template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
12416  class Singleton : SingletonImplT, public ISingleton {
12417 
12418  static auto getInternal() -> Singleton* {
12419  static Singleton* s_instance = nullptr;
12420  if( !s_instance ) {
12421  s_instance = new Singleton;
12422  addSingleton( s_instance );
12423  }
12424  return s_instance;
12425  }
12426 
12427  public:
12428  static auto get() -> InterfaceT const& {
12429  return *getInternal();
12430  }
12431  static auto getMutable() -> MutableInterfaceT& {
12432  return *getInternal();
12433  }
12434  };
12435 
12436 } // namespace Catch
12437 
12438 // end catch_singletons.hpp
12439 namespace Catch {
12440 
12441  namespace {
12442 
12443  class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
12444  private NonCopyable {
12445 
12446  public: // IRegistryHub
12447  RegistryHub() = default;
12448  IReporterRegistry const& getReporterRegistry() const override {
12449  return m_reporterRegistry;
12450  }
12451  ITestCaseRegistry const& getTestCaseRegistry() const override {
12452  return m_testCaseRegistry;
12453  }
12454  IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12455  return m_exceptionTranslatorRegistry;
12456  }
12457  ITagAliasRegistry const& getTagAliasRegistry() const override {
12458  return m_tagAliasRegistry;
12459  }
12460  StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12461  return m_exceptionRegistry;
12462  }
12463 
12464  public: // IMutableRegistryHub
12465  void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
12466  m_reporterRegistry.registerReporter( name, factory );
12467  }
12468  void registerListener( IReporterFactoryPtr const& factory ) override {
12469  m_reporterRegistry.registerListener( factory );
12470  }
12471  void registerTest( TestCase const& testInfo ) override {
12472  m_testCaseRegistry.registerTest( testInfo );
12473  }
12474  void registerTranslator( const IExceptionTranslator* translator ) override {
12475  m_exceptionTranslatorRegistry.registerTranslator( translator );
12476  }
12477  void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
12478  m_tagAliasRegistry.add( alias, tag, lineInfo );
12479  }
12480  void registerStartupException() noexcept override {
12481 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12482  m_exceptionRegistry.add(std::current_exception());
12483 #else
12484  CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12485 #endif
12486  }
12487  IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12488  return m_enumValuesRegistry;
12489  }
12490 
12491  private:
12492  TestRegistry m_testCaseRegistry;
12493  ReporterRegistry m_reporterRegistry;
12494  ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12495  TagAliasRegistry m_tagAliasRegistry;
12496  StartupExceptionRegistry m_exceptionRegistry;
12497  Detail::EnumValuesRegistry m_enumValuesRegistry;
12498  };
12499  }
12500 
12501  using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12502 
12503  IRegistryHub const& getRegistryHub() {
12504  return RegistryHubSingleton::get();
12505  }
12506  IMutableRegistryHub& getMutableRegistryHub() {
12507  return RegistryHubSingleton::getMutable();
12508  }
12509  void cleanUp() {
12510  cleanupSingletons();
12511  cleanUpContext();
12512  }
12513  std::string translateActiveException() {
12514  return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12515  }
12516 
12517 } // end namespace Catch
12518 // end catch_registry_hub.cpp
12519 // start catch_reporter_registry.cpp
12520 
12521 namespace Catch {
12522 
12523  ReporterRegistry::~ReporterRegistry() = default;
12524 
12525  IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
12526  auto it = m_factories.find( name );
12527  if( it == m_factories.end() )
12528  return nullptr;
12529  return it->second->create( ReporterConfig( config ) );
12530  }
12531 
12532  void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12533  m_factories.emplace(name, factory);
12534  }
12535  void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12536  m_listeners.push_back( factory );
12537  }
12538 
12539  IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12540  return m_factories;
12541  }
12542  IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12543  return m_listeners;
12544  }
12545 
12546 }
12547 // end catch_reporter_registry.cpp
12548 // start catch_result_type.cpp
12549 
12550 namespace Catch {
12551 
12552  bool isOk( ResultWas::OfType resultType ) {
12553  return ( resultType & ResultWas::FailureBit ) == 0;
12554  }
12555  bool isJustInfo( int flags ) {
12556  return flags == ResultWas::Info;
12557  }
12558 
12559  ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12560  return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12561  }
12562 
12563  bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12564  bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12565 
12566 } // end namespace Catch
12567 // end catch_result_type.cpp
12568 // start catch_run_context.cpp
12569 
12570 #include <cassert>
12571 #include <algorithm>
12572 #include <sstream>
12573 
12574 namespace Catch {
12575 
12576  namespace Generators {
12577  struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12578  GeneratorBasePtr m_generator;
12579 
12580  GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12581  : TrackerBase( nameAndLocation, ctx, parent )
12582  {}
12583  ~GeneratorTracker();
12584 
12585  static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12586  std::shared_ptr<GeneratorTracker> tracker;
12587 
12588  ITracker& currentTracker = ctx.currentTracker();
12589  // Under specific circumstances, the generator we want
12590  // to acquire is also the current tracker. If this is
12591  // the case, we have to avoid looking through current
12592  // tracker's children, and instead return the current
12593  // tracker.
12594  // A case where this check is important is e.g.
12595  // for (int i = 0; i < 5; ++i) {
12596  // int n = GENERATE(1, 2);
12597  // }
12598  //
12599  // without it, the code above creates 5 nested generators.
12600  if (currentTracker.nameAndLocation() == nameAndLocation) {
12601  auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12602  assert(thisTracker);
12603  assert(thisTracker->isGeneratorTracker());
12604  tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12605  } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12606  assert( childTracker );
12607  assert( childTracker->isGeneratorTracker() );
12608  tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12609  } else {
12610  tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
12611  currentTracker.addChild( tracker );
12612  }
12613 
12614  if( !tracker->isComplete() ) {
12615  tracker->open();
12616  }
12617 
12618  return *tracker;
12619  }
12620 
12621  // TrackerBase interface
12622  bool isGeneratorTracker() const override { return true; }
12623  auto hasGenerator() const -> bool override {
12624  return !!m_generator;
12625  }
12626  void close() override {
12627  TrackerBase::close();
12628  // If a generator has a child (it is followed by a section)
12629  // and none of its children have started, then we must wait
12630  // until later to start consuming its values.
12631  // This catches cases where `GENERATE` is placed between two
12632  // `SECTION`s.
12633  // **The check for m_children.empty cannot be removed**.
12634  // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12635  const bool should_wait_for_child = [&]() {
12636  // No children -> nobody to wait for
12637  if ( m_children.empty() ) {
12638  return false;
12639  }
12640  // If at least one child started executing, don't wait
12641  if ( std::find_if(
12642  m_children.begin(),
12643  m_children.end(),
12644  []( TestCaseTracking::ITrackerPtr tracker ) {
12645  return tracker->hasStarted();
12646  } ) != m_children.end() ) {
12647  return false;
12648  }
12649 
12650  // No children have started. We need to check if they _can_
12651  // start, and thus we should wait for them, or they cannot
12652  // start (due to filters), and we shouldn't wait for them
12653  auto* parent = m_parent;
12654  // This is safe: there is always at least one section
12655  // tracker in a test case tracking tree
12656  while ( !parent->isSectionTracker() ) {
12657  parent = &( parent->parent() );
12658  }
12659  assert( parent &&
12660  "Missing root (test case) level section" );
12661 
12662  auto const& parentSection =
12663  static_cast<SectionTracker&>( *parent );
12664  auto const& filters = parentSection.getFilters();
12665  // No filters -> no restrictions on running sections
12666  if ( filters.empty() ) {
12667  return true;
12668  }
12669 
12670  for ( auto const& child : m_children ) {
12671  if ( child->isSectionTracker() &&
12672  std::find( filters.begin(),
12673  filters.end(),
12674  static_cast<SectionTracker&>( *child )
12675  .trimmedName() ) !=
12676  filters.end() ) {
12677  return true;
12678  }
12679  }
12680  return false;
12681  }();
12682 
12683  // This check is a bit tricky, because m_generator->next()
12684  // has a side-effect, where it consumes generator's current
12685  // value, but we do not want to invoke the side-effect if
12686  // this generator is still waiting for any child to start.
12687  if ( should_wait_for_child ||
12688  ( m_runState == CompletedSuccessfully &&
12689  m_generator->next() ) ) {
12690  m_children.clear();
12691  m_runState = Executing;
12692  }
12693  }
12694 
12695  // IGeneratorTracker interface
12696  auto getGenerator() const -> GeneratorBasePtr const& override {
12697  return m_generator;
12698  }
12699  void setGenerator( GeneratorBasePtr&& generator ) override {
12700  m_generator = std::move( generator );
12701  }
12702  };
12703  GeneratorTracker::~GeneratorTracker() {}
12704  }
12705 
12706  RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12707  : m_runInfo(_config->name()),
12708  m_context(getCurrentMutableContext()),
12709  m_config(_config),
12710  m_reporter(std::move(reporter)),
12711  m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12712  m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12713  {
12714  m_context.setRunner(this);
12715  m_context.setConfig(m_config);
12716  m_context.setResultCapture(this);
12717  m_reporter->testRunStarting(m_runInfo);
12718  }
12719 
12720  RunContext::~RunContext() {
12721  m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12722  }
12723 
12724  void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12725  m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12726  }
12727 
12728  void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12729  m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12730  }
12731 
12732  Totals RunContext::runTest(TestCase const& testCase) {
12733  Totals prevTotals = m_totals;
12734 
12735  std::string redirectedCout;
12736  std::string redirectedCerr;
12737 
12738  auto const& testInfo = testCase.getTestCaseInfo();
12739 
12740  m_reporter->testCaseStarting(testInfo);
12741 
12742  m_activeTestCase = &testCase;
12743 
12744  ITracker& rootTracker = m_trackerContext.startRun();
12745  assert(rootTracker.isSectionTracker());
12746  static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12747  do {
12748  m_trackerContext.startCycle();
12749  m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12750  runCurrentTest(redirectedCout, redirectedCerr);
12751  } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12752 
12753  Totals deltaTotals = m_totals.delta(prevTotals);
12754  if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12755  deltaTotals.assertions.failed++;
12756  deltaTotals.testCases.passed--;
12757  deltaTotals.testCases.failed++;
12758  }
12759  m_totals.testCases += deltaTotals.testCases;
12760  m_reporter->testCaseEnded(TestCaseStats(testInfo,
12761  deltaTotals,
12762  redirectedCout,
12763  redirectedCerr,
12764  aborting()));
12765 
12766  m_activeTestCase = nullptr;
12767  m_testCaseTracker = nullptr;
12768 
12769  return deltaTotals;
12770  }
12771 
12772  IConfigPtr RunContext::config() const {
12773  return m_config;
12774  }
12775 
12776  IStreamingReporter& RunContext::reporter() const {
12777  return *m_reporter;
12778  }
12779 
12780  void RunContext::assertionEnded(AssertionResult const & result) {
12781  if (result.getResultType() == ResultWas::Ok) {
12782  m_totals.assertions.passed++;
12783  m_lastAssertionPassed = true;
12784  } else if (!result.isOk()) {
12785  m_lastAssertionPassed = false;
12786  if( m_activeTestCase->getTestCaseInfo().okToFail() )
12787  m_totals.assertions.failedButOk++;
12788  else
12789  m_totals.assertions.failed++;
12790  }
12791  else {
12792  m_lastAssertionPassed = true;
12793  }
12794 
12795  // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12796  // and should be let to clear themselves out.
12797  static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12798 
12799  if (result.getResultType() != ResultWas::Warning)
12800  m_messageScopes.clear();
12801 
12802  // Reset working state
12803  resetAssertionInfo();
12804  m_lastResult = result;
12805  }
12806  void RunContext::resetAssertionInfo() {
12807  m_lastAssertionInfo.macroName = StringRef();
12808  m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12809  }
12810 
12811  bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12812  ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12813  if (!sectionTracker.isOpen())
12814  return false;
12815  m_activeSections.push_back(&sectionTracker);
12816 
12817  m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12818 
12819  m_reporter->sectionStarting(sectionInfo);
12820 
12821  assertions = m_totals.assertions;
12822 
12823  return true;
12824  }
12825  auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12826  using namespace Generators;
12827  GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12828  TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12829  m_lastAssertionInfo.lineInfo = lineInfo;
12830  return tracker;
12831  }
12832 
12833  bool RunContext::testForMissingAssertions(Counts& assertions) {
12834  if (assertions.total() != 0)
12835  return false;
12836  if (!m_config->warnAboutMissingAssertions())
12837  return false;
12838  if (m_trackerContext.currentTracker().hasChildren())
12839  return false;
12840  m_totals.assertions.failed++;
12841  assertions.failed++;
12842  return true;
12843  }
12844 
12845  void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12846  Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12847  bool missingAssertions = testForMissingAssertions(assertions);
12848 
12849  if (!m_activeSections.empty()) {
12850  m_activeSections.back()->close();
12851  m_activeSections.pop_back();
12852  }
12853 
12854  m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12855  m_messages.clear();
12856  m_messageScopes.clear();
12857  }
12858 
12859  void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12860  if (m_unfinishedSections.empty())
12861  m_activeSections.back()->fail();
12862  else
12863  m_activeSections.back()->close();
12864  m_activeSections.pop_back();
12865 
12866  m_unfinishedSections.push_back(endInfo);
12867  }
12868 
12869 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12870  void RunContext::benchmarkPreparing(std::string const& name) {
12871  m_reporter->benchmarkPreparing(name);
12872  }
12873  void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12874  m_reporter->benchmarkStarting( info );
12875  }
12876  void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12877  m_reporter->benchmarkEnded( stats );
12878  }
12879  void RunContext::benchmarkFailed(std::string const & error) {
12880  m_reporter->benchmarkFailed(error);
12881  }
12882 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12883 
12884  void RunContext::pushScopedMessage(MessageInfo const & message) {
12885  m_messages.push_back(message);
12886  }
12887 
12888  void RunContext::popScopedMessage(MessageInfo const & message) {
12889  m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12890  }
12891 
12892  void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12893  m_messageScopes.emplace_back( builder );
12894  }
12895 
12896  std::string RunContext::getCurrentTestName() const {
12897  return m_activeTestCase
12898  ? m_activeTestCase->getTestCaseInfo().name
12899  : std::string();
12900  }
12901 
12902  const AssertionResult * RunContext::getLastResult() const {
12903  return &(*m_lastResult);
12904  }
12905 
12906  void RunContext::exceptionEarlyReported() {
12907  m_shouldReportUnexpected = false;
12908  }
12909 
12910  void RunContext::handleFatalErrorCondition( StringRef message ) {
12911  // First notify reporter that bad things happened
12912  m_reporter->fatalErrorEncountered(message);
12913 
12914  // Don't rebuild the result -- the stringification itself can cause more fatal errors
12915  // Instead, fake a result data.
12916  AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12917  tempResult.message = static_cast<std::string>(message);
12918  AssertionResult result(m_lastAssertionInfo, tempResult);
12919 
12920  assertionEnded(result);
12921 
12922  handleUnfinishedSections();
12923 
12924  // Recreate section for test case (as we will lose the one that was in scope)
12925  auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12926  SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12927 
12928  Counts assertions;
12929  assertions.failed = 1;
12930  SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12931  m_reporter->sectionEnded(testCaseSectionStats);
12932 
12933  auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12934 
12935  Totals deltaTotals;
12936  deltaTotals.testCases.failed = 1;
12937  deltaTotals.assertions.failed = 1;
12938  m_reporter->testCaseEnded(TestCaseStats(testInfo,
12939  deltaTotals,
12940  std::string(),
12941  std::string(),
12942  false));
12943  m_totals.testCases.failed++;
12944  testGroupEnded(std::string(), m_totals, 1, 1);
12945  m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12946  }
12947 
12948  bool RunContext::lastAssertionPassed() {
12949  return m_lastAssertionPassed;
12950  }
12951 
12952  void RunContext::assertionPassed() {
12953  m_lastAssertionPassed = true;
12954  ++m_totals.assertions.passed;
12955  resetAssertionInfo();
12956  m_messageScopes.clear();
12957  }
12958 
12959  bool RunContext::aborting() const {
12960  return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12961  }
12962 
12963  void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12964  auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12965  SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12966  m_reporter->sectionStarting(testCaseSection);
12967  Counts prevAssertions = m_totals.assertions;
12968  double duration = 0;
12969  m_shouldReportUnexpected = true;
12970  m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12971 
12972  seedRng(*m_config);
12973 
12974  Timer timer;
12975  CATCH_TRY {
12976  if (m_reporter->getPreferences().shouldRedirectStdOut) {
12977 #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12978  RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12979 
12980  timer.start();
12981  invokeActiveTestCase();
12982 #else
12983  OutputRedirect r(redirectedCout, redirectedCerr);
12984  timer.start();
12985  invokeActiveTestCase();
12986 #endif
12987  } else {
12988  timer.start();
12989  invokeActiveTestCase();
12990  }
12991  duration = timer.getElapsedSeconds();
12992  } CATCH_CATCH_ANON (TestFailureException&) {
12993  // This just means the test was aborted due to failure
12994  } CATCH_CATCH_ALL {
12995  // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
12996  // are reported without translation at the point of origin.
12997  if( m_shouldReportUnexpected ) {
12998  AssertionReaction dummyReaction;
12999  handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13000  }
13001  }
13002  Counts assertions = m_totals.assertions - prevAssertions;
13003  bool missingAssertions = testForMissingAssertions(assertions);
13004 
13005  m_testCaseTracker->close();
13006  handleUnfinishedSections();
13007  m_messages.clear();
13008  m_messageScopes.clear();
13009 
13010  SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13011  m_reporter->sectionEnded(testCaseSectionStats);
13012  }
13013 
13014  void RunContext::invokeActiveTestCase() {
13015  FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13016  m_activeTestCase->invoke();
13017  }
13018 
13019  void RunContext::handleUnfinishedSections() {
13020  // If sections ended prematurely due to an exception we stored their
13021  // infos here so we can tear them down outside the unwind process.
13022  for (auto it = m_unfinishedSections.rbegin(),
13023  itEnd = m_unfinishedSections.rend();
13024  it != itEnd;
13025  ++it)
13026  sectionEnded(*it);
13027  m_unfinishedSections.clear();
13028  }
13029 
13030  void RunContext::handleExpr(
13031  AssertionInfo const& info,
13032  ITransientExpression const& expr,
13033  AssertionReaction& reaction
13034  ) {
13035  m_reporter->assertionStarting( info );
13036 
13037  bool negated = isFalseTest( info.resultDisposition );
13038  bool result = expr.getResult() != negated;
13039 
13040  if( result ) {
13041  if (!m_includeSuccessfulResults) {
13042  assertionPassed();
13043  }
13044  else {
13045  reportExpr(info, ResultWas::Ok, &expr, negated);
13046  }
13047  }
13048  else {
13049  reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13050  populateReaction( reaction );
13051  }
13052  }
13053  void RunContext::reportExpr(
13054  AssertionInfo const &info,
13055  ResultWas::OfType resultType,
13056  ITransientExpression const *expr,
13057  bool negated ) {
13058 
13059  m_lastAssertionInfo = info;
13060  AssertionResultData data( resultType, LazyExpression( negated ) );
13061 
13062  AssertionResult assertionResult{ info, data };
13063  assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13064 
13065  assertionEnded( assertionResult );
13066  }
13067 
13068  void RunContext::handleMessage(
13069  AssertionInfo const& info,
13070  ResultWas::OfType resultType,
13071  StringRef const& message,
13072  AssertionReaction& reaction
13073  ) {
13074  m_reporter->assertionStarting( info );
13075 
13076  m_lastAssertionInfo = info;
13077 
13078  AssertionResultData data( resultType, LazyExpression( false ) );
13079  data.message = static_cast<std::string>(message);
13080  AssertionResult assertionResult{ m_lastAssertionInfo, data };
13081  assertionEnded( assertionResult );
13082  if( !assertionResult.isOk() )
13083  populateReaction( reaction );
13084  }
13085  void RunContext::handleUnexpectedExceptionNotThrown(
13086  AssertionInfo const& info,
13087  AssertionReaction& reaction
13088  ) {
13089  handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13090  }
13091 
13092  void RunContext::handleUnexpectedInflightException(
13093  AssertionInfo const& info,
13094  std::string const& message,
13095  AssertionReaction& reaction
13096  ) {
13097  m_lastAssertionInfo = info;
13098 
13099  AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13100  data.message = message;
13101  AssertionResult assertionResult{ info, data };
13102  assertionEnded( assertionResult );
13103  populateReaction( reaction );
13104  }
13105 
13106  void RunContext::populateReaction( AssertionReaction& reaction ) {
13107  reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13108  reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13109  }
13110 
13111  void RunContext::handleIncomplete(
13112  AssertionInfo const& info
13113  ) {
13114  m_lastAssertionInfo = info;
13115 
13116  AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13117  data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13118  AssertionResult assertionResult{ info, data };
13119  assertionEnded( assertionResult );
13120  }
13121  void RunContext::handleNonExpr(
13122  AssertionInfo const &info,
13123  ResultWas::OfType resultType,
13124  AssertionReaction &reaction
13125  ) {
13126  m_lastAssertionInfo = info;
13127 
13128  AssertionResultData data( resultType, LazyExpression( false ) );
13129  AssertionResult assertionResult{ info, data };
13130  assertionEnded( assertionResult );
13131 
13132  if( !assertionResult.isOk() )
13133  populateReaction( reaction );
13134  }
13135 
13136  IResultCapture& getResultCapture() {
13137  if (auto* capture = getCurrentContext().getResultCapture())
13138  return *capture;
13139  else
13140  CATCH_INTERNAL_ERROR("No result capture instance");
13141  }
13142 
13143  void seedRng(IConfig const& config) {
13144  if (config.rngSeed() != 0) {
13145  std::srand(config.rngSeed());
13146  rng().seed(config.rngSeed());
13147  }
13148  }
13149 
13150  unsigned int rngSeed() {
13151  return getCurrentContext().getConfig()->rngSeed();
13152  }
13153 
13154 }
13155 // end catch_run_context.cpp
13156 // start catch_section.cpp
13157 
13158 namespace Catch {
13159 
13160  Section::Section( SectionInfo const& info )
13161  : m_info( info ),
13162  m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13163  {
13164  m_timer.start();
13165  }
13166 
13167  Section::~Section() {
13168  if( m_sectionIncluded ) {
13169  SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13170  if( uncaught_exceptions() )
13171  getResultCapture().sectionEndedEarly( endInfo );
13172  else
13173  getResultCapture().sectionEnded( endInfo );
13174  }
13175  }
13176 
13177  // This indicates whether the section should be executed or not
13178  Section::operator bool() const {
13179  return m_sectionIncluded;
13180  }
13181 
13182 } // end namespace Catch
13183 // end catch_section.cpp
13184 // start catch_section_info.cpp
13185 
13186 namespace Catch {
13187 
13188  SectionInfo::SectionInfo
13189  ( SourceLineInfo const& _lineInfo,
13190  std::string const& _name )
13191  : name( _name ),
13192  lineInfo( _lineInfo )
13193  {}
13194 
13195 } // end namespace Catch
13196 // end catch_section_info.cpp
13197 // start catch_session.cpp
13198 
13199 // start catch_session.h
13200 
13201 #include <memory>
13202 
13203 namespace Catch {
13204 
13205  class Session : NonCopyable {
13206  public:
13207 
13208  Session();
13209  ~Session() override;
13210 
13211  void showHelp() const;
13212  void libIdentify();
13213 
13214  int applyCommandLine( int argc, char const * const * argv );
13215  #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13216  int applyCommandLine( int argc, wchar_t const * const * argv );
13217  #endif
13218 
13219  void useConfigData( ConfigData const& configData );
13220 
13221  template<typename CharT>
13222  int run(int argc, CharT const * const argv[]) {
13223  if (m_startupExceptions)
13224  return 1;
13225  int returnCode = applyCommandLine(argc, argv);
13226  if (returnCode == 0)
13227  returnCode = run();
13228  return returnCode;
13229  }
13230 
13231  int run();
13232 
13233  clara::Parser const& cli() const;
13234  void cli( clara::Parser const& newParser );
13235  ConfigData& configData();
13236  Config& config();
13237  private:
13238  int runInternal();
13239 
13240  clara::Parser m_cli;
13241  ConfigData m_configData;
13242  std::shared_ptr<Config> m_config;
13243  bool m_startupExceptions = false;
13244  };
13245 
13246 } // end namespace Catch
13247 
13248 // end catch_session.h
13249 // start catch_version.h
13250 
13251 #include <iosfwd>
13252 
13253 namespace Catch {
13254 
13255  // Versioning information
13256  struct Version {
13257  Version( Version const& ) = delete;
13258  Version& operator=( Version const& ) = delete;
13259  Version( unsigned int _majorVersion,
13260  unsigned int _minorVersion,
13261  unsigned int _patchNumber,
13262  char const * const _branchName,
13263  unsigned int _buildNumber );
13264 
13265  unsigned int const majorVersion;
13266  unsigned int const minorVersion;
13267  unsigned int const patchNumber;
13268 
13269  // buildNumber is only used if branchName is not null
13270  char const * const branchName;
13271  unsigned int const buildNumber;
13272 
13273  friend std::ostream& operator << ( std::ostream& os, Version const& version );
13274  };
13275 
13276  Version const& libraryVersion();
13277 }
13278 
13279 // end catch_version.h
13280 #include <cstdlib>
13281 #include <iomanip>
13282 #include <set>
13283 #include <iterator>
13284 
13285 namespace Catch {
13286 
13287  namespace {
13288  const int MaxExitCode = 255;
13289 
13290  IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13291  auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13292  CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13293 
13294  return reporter;
13295  }
13296 
13297  IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13298  if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13299  return createReporter(config->getReporterName(), config);
13300  }
13301 
13302  // On older platforms, returning std::unique_ptr<ListeningReporter>
13303  // when the return type is std::unique_ptr<IStreamingReporter>
13304  // doesn't compile without a std::move call. However, this causes
13305  // a warning on newer platforms. Thus, we have to work around
13306  // it a bit and downcast the pointer manually.
13307  auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13308  auto& multi = static_cast<ListeningReporter&>(*ret);
13309  auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13310  for (auto const& listener : listeners) {
13311  multi.addListener(listener->create(Catch::ReporterConfig(config)));
13312  }
13313  multi.addReporter(createReporter(config->getReporterName(), config));
13314  return ret;
13315  }
13316 
13317  class TestGroup {
13318  public:
13319  explicit TestGroup(std::shared_ptr<Config> const& config)
13320  : m_config{config}
13321  , m_context{config, makeReporter(config)}
13322  {
13323  auto const& allTestCases = getAllTestCasesSorted(*m_config);
13324  m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13325  auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13326 
13327  if (m_matches.empty() && invalidArgs.empty()) {
13328  for (auto const& test : allTestCases)
13329  if (!test.isHidden())
13330  m_tests.emplace(&test);
13331  } else {
13332  for (auto const& match : m_matches)
13333  m_tests.insert(match.tests.begin(), match.tests.end());
13334  }
13335  }
13336 
13337  Totals execute() {
13338  auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13339  Totals totals;
13340  m_context.testGroupStarting(m_config->name(), 1, 1);
13341  for (auto const& testCase : m_tests) {
13342  if (!m_context.aborting())
13343  totals += m_context.runTest(*testCase);
13344  else
13345  m_context.reporter().skipTest(*testCase);
13346  }
13347 
13348  for (auto const& match : m_matches) {
13349  if (match.tests.empty()) {
13350  m_context.reporter().noMatchingTestCases(match.name);
13351  totals.error = -1;
13352  }
13353  }
13354 
13355  if (!invalidArgs.empty()) {
13356  for (auto const& invalidArg: invalidArgs)
13357  m_context.reporter().reportInvalidArguments(invalidArg);
13358  }
13359 
13360  m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13361  return totals;
13362  }
13363 
13364  private:
13365  using Tests = std::set<TestCase const*>;
13366 
13367  std::shared_ptr<Config> m_config;
13368  RunContext m_context;
13369  Tests m_tests;
13370  TestSpec::Matches m_matches;
13371  };
13372 
13373  void applyFilenamesAsTags(Catch::IConfig const& config) {
13374  auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13375  for (auto& testCase : tests) {
13376  auto tags = testCase.tags;
13377 
13378  std::string filename = testCase.lineInfo.file;
13379  auto lastSlash = filename.find_last_of("\\/");
13380  if (lastSlash != std::string::npos) {
13381  filename.erase(0, lastSlash);
13382  filename[0] = '#';
13383  }
13384 
13385  auto lastDot = filename.find_last_of('.');
13386  if (lastDot != std::string::npos) {
13387  filename.erase(lastDot);
13388  }
13389 
13390  tags.push_back(std::move(filename));
13391  setTags(testCase, tags);
13392  }
13393  }
13394 
13395  } // anon namespace
13396 
13397  Session::Session() {
13398  static bool alreadyInstantiated = false;
13399  if( alreadyInstantiated ) {
13400  CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
13401  CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13402  }
13403 
13404  // There cannot be exceptions at startup in no-exception mode.
13405 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13406  const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13407  if ( !exceptions.empty() ) {
13408  config();
13409  getCurrentMutableContext().setConfig(m_config);
13410 
13411  m_startupExceptions = true;
13412  Colour colourGuard( Colour::Red );
13413  Catch::cerr() << "Errors occurred during startup!" << '\n';
13414  // iterate over all exceptions and notify user
13415  for ( const auto& ex_ptr : exceptions ) {
13416  try {
13417  std::rethrow_exception(ex_ptr);
13418  } catch ( std::exception const& ex ) {
13419  Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
13420  }
13421  }
13422  }
13423 #endif
13424 
13425  alreadyInstantiated = true;
13426  m_cli = makeCommandLineParser( m_configData );
13427  }
13428  Session::~Session() {
13429  Catch::cleanUp();
13430  }
13431 
13432  void Session::showHelp() const {
13433  Catch::cout()
13434  << "\nCatch v" << libraryVersion() << "\n"
13435  << m_cli << std::endl
13436  << "For more detailed usage please see the project docs\n" << std::endl;
13437  }
13438  void Session::libIdentify() {
13439  Catch::cout()
13440  << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13441  << std::left << std::setw(16) << "category: " << "testframework\n"
13442  << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13443  << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13444  }
13445 
13446  int Session::applyCommandLine( int argc, char const * const * argv ) {
13447  if( m_startupExceptions )
13448  return 1;
13449 
13450  auto result = m_cli.parse( clara::Args( argc, argv ) );
13451  if( !result ) {
13452  config();
13453  getCurrentMutableContext().setConfig(m_config);
13454  Catch::cerr()
13455  << Colour( Colour::Red )
13456  << "\nError(s) in input:\n"
13457  << Column( result.errorMessage() ).indent( 2 )
13458  << "\n\n";
13459  Catch::cerr() << "Run with -? for usage\n" << std::endl;
13460  return MaxExitCode;
13461  }
13462 
13463  if( m_configData.showHelp )
13464  showHelp();
13465  if( m_configData.libIdentify )
13466  libIdentify();
13467  m_config.reset();
13468  return 0;
13469  }
13470 
13471 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13472  int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
13473 
13474  char **utf8Argv = new char *[ argc ];
13475 
13476  for ( int i = 0; i < argc; ++i ) {
13477  int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
13478 
13479  utf8Argv[ i ] = new char[ bufSize ];
13480 
13481  WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
13482  }
13483 
13484  int returnCode = applyCommandLine( argc, utf8Argv );
13485 
13486  for ( int i = 0; i < argc; ++i )
13487  delete [] utf8Argv[ i ];
13488 
13489  delete [] utf8Argv;
13490 
13491  return returnCode;
13492  }
13493 #endif
13494 
13495  void Session::useConfigData( ConfigData const& configData ) {
13496  m_configData = configData;
13497  m_config.reset();
13498  }
13499 
13500  int Session::run() {
13501  if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13502  Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13503  static_cast<void>(std::getchar());
13504  }
13505  int exitCode = runInternal();
13506  if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13507  Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13508  static_cast<void>(std::getchar());
13509  }
13510  return exitCode;
13511  }
13512 
13513  clara::Parser const& Session::cli() const {
13514  return m_cli;
13515  }
13516  void Session::cli( clara::Parser const& newParser ) {
13517  m_cli = newParser;
13518  }
13519  ConfigData& Session::configData() {
13520  return m_configData;
13521  }
13522  Config& Session::config() {
13523  if( !m_config )
13524  m_config = std::make_shared<Config>( m_configData );
13525  return *m_config;
13526  }
13527 
13528  int Session::runInternal() {
13529  if( m_startupExceptions )
13530  return 1;
13531 
13532  if (m_configData.showHelp || m_configData.libIdentify) {
13533  return 0;
13534  }
13535 
13536  CATCH_TRY {
13537  config(); // Force config to be constructed
13538 
13539  seedRng( *m_config );
13540 
13541  if( m_configData.filenamesAsTags )
13542  applyFilenamesAsTags( *m_config );
13543 
13544  // Handle list request
13545  if( Option<std::size_t> listed = list( m_config ) )
13546  return static_cast<int>( *listed );
13547 
13548  TestGroup tests { m_config };
13549  auto const totals = tests.execute();
13550 
13551  if( m_config->warnAboutNoTests() && totals.error == -1 )
13552  return 2;
13553 
13554  // Note that on unices only the lower 8 bits are usually used, clamping
13555  // the return value to 255 prevents false negative when some multiple
13556  // of 256 tests has failed
13557  return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13558  }
13559 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13560  catch( std::exception& ex ) {
13561  Catch::cerr() << ex.what() << std::endl;
13562  return MaxExitCode;
13563  }
13564 #endif
13565  }
13566 
13567 } // end namespace Catch
13568 // end catch_session.cpp
13569 // start catch_singletons.cpp
13570 
13571 #include <vector>
13572 
13573 namespace Catch {
13574 
13575  namespace {
13576  static auto getSingletons() -> std::vector<ISingleton*>*& {
13577  static std::vector<ISingleton*>* g_singletons = nullptr;
13578  if( !g_singletons )
13579  g_singletons = new std::vector<ISingleton*>();
13580  return g_singletons;
13581  }
13582  }
13583 
13584  ISingleton::~ISingleton() {}
13585 
13586  void addSingleton(ISingleton* singleton ) {
13587  getSingletons()->push_back( singleton );
13588  }
13589  void cleanupSingletons() {
13590  auto& singletons = getSingletons();
13591  for( auto singleton : *singletons )
13592  delete singleton;
13593  delete singletons;
13594  singletons = nullptr;
13595  }
13596 
13597 } // namespace Catch
13598 // end catch_singletons.cpp
13599 // start catch_startup_exception_registry.cpp
13600 
13601 #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13602 namespace Catch {
13603 void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
13604  CATCH_TRY {
13605  m_exceptions.push_back(exception);
13606  } CATCH_CATCH_ALL {
13607  // If we run out of memory during start-up there's really not a lot more we can do about it
13608  std::terminate();
13609  }
13610  }
13611 
13612  std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13613  return m_exceptions;
13614  }
13615 
13616 } // end namespace Catch
13617 #endif
13618 // end catch_startup_exception_registry.cpp
13619 // start catch_stream.cpp
13620 
13621 #include <cstdio>
13622 #include <iostream>
13623 #include <fstream>
13624 #include <sstream>
13625 #include <vector>
13626 #include <memory>
13627 
13628 namespace Catch {
13629 
13630  Catch::IStream::~IStream() = default;
13631 
13632  namespace Detail { namespace {
13633  template<typename WriterF, std::size_t bufferSize=256>
13634  class StreamBufImpl : public std::streambuf {
13635  char data[bufferSize];
13636  WriterF m_writer;
13637 
13638  public:
13639  StreamBufImpl() {
13640  setp( data, data + sizeof(data) );
13641  }
13642 
13643  ~StreamBufImpl() noexcept {
13644  StreamBufImpl::sync();
13645  }
13646 
13647  private:
13648  int overflow( int c ) override {
13649  sync();
13650 
13651  if( c != EOF ) {
13652  if( pbase() == epptr() )
13653  m_writer( std::string( 1, static_cast<char>( c ) ) );
13654  else
13655  sputc( static_cast<char>( c ) );
13656  }
13657  return 0;
13658  }
13659 
13660  int sync() override {
13661  if( pbase() != pptr() ) {
13662  m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13663  setp( pbase(), epptr() );
13664  }
13665  return 0;
13666  }
13667  };
13668 
13670 
13671  struct OutputDebugWriter {
13672 
13673  void operator()( std::string const&str ) {
13674  writeToDebugConsole( str );
13675  }
13676  };
13677 
13679 
13680  class FileStream : public IStream {
13681  mutable std::ofstream m_ofs;
13682  public:
13683  FileStream( StringRef filename ) {
13684  m_ofs.open( filename.c_str() );
13685  CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13686  }
13687  ~FileStream() override = default;
13688  public: // IStream
13689  std::ostream& stream() const override {
13690  return m_ofs;
13691  }
13692  };
13693 
13695 
13696  class CoutStream : public IStream {
13697  mutable std::ostream m_os;
13698  public:
13699  // Store the streambuf from cout up-front because
13700  // cout may get redirected when running tests
13701  CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13702  ~CoutStream() override = default;
13703 
13704  public: // IStream
13705  std::ostream& stream() const override { return m_os; }
13706  };
13707 
13709 
13710  class DebugOutStream : public IStream {
13711  std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13712  mutable std::ostream m_os;
13713  public:
13714  DebugOutStream()
13715  : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13716  m_os( m_streamBuf.get() )
13717  {}
13718 
13719  ~DebugOutStream() override = default;
13720 
13721  public: // IStream
13722  std::ostream& stream() const override { return m_os; }
13723  };
13724 
13725  }} // namespace anon::detail
13726 
13728 
13729  auto makeStream( StringRef const &filename ) -> IStream const* {
13730  if( filename.empty() )
13731  return new Detail::CoutStream();
13732  else if( filename[0] == '%' ) {
13733  if( filename == "%debug" )
13734  return new Detail::DebugOutStream();
13735  else
13736  CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13737  }
13738  else
13739  return new Detail::FileStream( filename );
13740  }
13741 
13742  // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13743  struct StringStreams {
13744  std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13745  std::vector<std::size_t> m_unused;
13746  std::ostringstream m_referenceStream; // Used for copy state/ flags from
13747 
13748  auto add() -> std::size_t {
13749  if( m_unused.empty() ) {
13750  m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13751  return m_streams.size()-1;
13752  }
13753  else {
13754  auto index = m_unused.back();
13755  m_unused.pop_back();
13756  return index;
13757  }
13758  }
13759 
13760  void release( std::size_t index ) {
13761  m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13762  m_unused.push_back(index);
13763  }
13764  };
13765 
13766  ReusableStringStream::ReusableStringStream()
13767  : m_index( Singleton<StringStreams>::getMutable().add() ),
13768  m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13769  {}
13770 
13771  ReusableStringStream::~ReusableStringStream() {
13772  static_cast<std::ostringstream*>( m_oss )->str("");
13773  m_oss->clear();
13774  Singleton<StringStreams>::getMutable().release( m_index );
13775  }
13776 
13777  auto ReusableStringStream::str() const -> std::string {
13778  return static_cast<std::ostringstream*>( m_oss )->str();
13779  }
13780 
13782 
13783 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
13784  std::ostream& cout() { return std::cout; }
13785  std::ostream& cerr() { return std::cerr; }
13786  std::ostream& clog() { return std::clog; }
13787 #endif
13788 }
13789 // end catch_stream.cpp
13790 // start catch_string_manip.cpp
13791 
13792 #include <algorithm>
13793 #include <ostream>
13794 #include <cstring>
13795 #include <cctype>
13796 #include <vector>
13797 
13798 namespace Catch {
13799 
13800  namespace {
13801  char toLowerCh(char c) {
13802  return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13803  }
13804  }
13805 
13806  bool startsWith( std::string const& s, std::string const& prefix ) {
13807  return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13808  }
13809  bool startsWith( std::string const& s, char prefix ) {
13810  return !s.empty() && s[0] == prefix;
13811  }
13812  bool endsWith( std::string const& s, std::string const& suffix ) {
13813  return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13814  }
13815  bool endsWith( std::string const& s, char suffix ) {
13816  return !s.empty() && s[s.size()-1] == suffix;
13817  }
13818  bool contains( std::string const& s, std::string const& infix ) {
13819  return s.find( infix ) != std::string::npos;
13820  }
13821  void toLowerInPlace( std::string& s ) {
13822  std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13823  }
13824  std::string toLower( std::string const& s ) {
13825  std::string lc = s;
13826  toLowerInPlace( lc );
13827  return lc;
13828  }
13829  std::string trim( std::string const& str ) {
13830  static char const* whitespaceChars = "\n\r\t ";
13831  std::string::size_type start = str.find_first_not_of( whitespaceChars );
13832  std::string::size_type end = str.find_last_not_of( whitespaceChars );
13833 
13834  return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13835  }
13836 
13837  StringRef trim(StringRef ref) {
13838  const auto is_ws = [](char c) {
13839  return c == ' ' || c == '\t' || c == '\n' || c == '\r';
13840  };
13841  size_t real_begin = 0;
13842  while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13843  size_t real_end = ref.size();
13844  while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13845 
13846  return ref.substr(real_begin, real_end - real_begin);
13847  }
13848 
13849  bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13850  bool replaced = false;
13851  std::size_t i = str.find( replaceThis );
13852  while( i != std::string::npos ) {
13853  replaced = true;
13854  str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13855  if( i < str.size()-withThis.size() )
13856  i = str.find( replaceThis, i+withThis.size() );
13857  else
13858  i = std::string::npos;
13859  }
13860  return replaced;
13861  }
13862 
13863  std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13864  std::vector<StringRef> subStrings;
13865  std::size_t start = 0;
13866  for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13867  if( str[pos] == delimiter ) {
13868  if( pos - start > 1 )
13869  subStrings.push_back( str.substr( start, pos-start ) );
13870  start = pos+1;
13871  }
13872  }
13873  if( start < str.size() )
13874  subStrings.push_back( str.substr( start, str.size()-start ) );
13875  return subStrings;
13876  }
13877 
13878  pluralise::pluralise( std::size_t count, std::string const& label )
13879  : m_count( count ),
13880  m_label( label )
13881  {}
13882 
13883  std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13884  os << pluraliser.m_count << ' ' << pluraliser.m_label;
13885  if( pluraliser.m_count != 1 )
13886  os << 's';
13887  return os;
13888  }
13889 
13890 }
13891 // end catch_string_manip.cpp
13892 // start catch_stringref.cpp
13893 
13894 #include <algorithm>
13895 #include <ostream>
13896 #include <cstring>
13897 #include <cstdint>
13898 
13899 namespace Catch {
13900  StringRef::StringRef( char const* rawChars ) noexcept
13901  : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13902  {}
13903 
13904  auto StringRef::c_str() const -> char const* {
13905  CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
13906  return m_start;
13907  }
13908  auto StringRef::data() const noexcept -> char const* {
13909  return m_start;
13910  }
13911 
13912  auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13913  if (start < m_size) {
13914  return StringRef(m_start + start, (std::min)(m_size - start, size));
13915  } else {
13916  return StringRef();
13917  }
13918  }
13919  auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13920  return m_size == other.m_size
13921  && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13922  }
13923 
13924  auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13925  return os.write(str.data(), str.size());
13926  }
13927 
13928  auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13929  lhs.append(rhs.data(), rhs.size());
13930  return lhs;
13931  }
13932 
13933 } // namespace Catch
13934 // end catch_stringref.cpp
13935 // start catch_tag_alias.cpp
13936 
13937 namespace Catch {
13938  TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13939 }
13940 // end catch_tag_alias.cpp
13941 // start catch_tag_alias_autoregistrar.cpp
13942 
13943 namespace Catch {
13944 
13945  RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13946  CATCH_TRY {
13947  getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13948  } CATCH_CATCH_ALL {
13949  // Do not throw when constructing global objects, instead register the exception to be processed later
13950  getMutableRegistryHub().registerStartupException();
13951  }
13952  }
13953 
13954 }
13955 // end catch_tag_alias_autoregistrar.cpp
13956 // start catch_tag_alias_registry.cpp
13957 
13958 #include <sstream>
13959 
13960 namespace Catch {
13961 
13962  TagAliasRegistry::~TagAliasRegistry() {}
13963 
13964  TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13965  auto it = m_registry.find( alias );
13966  if( it != m_registry.end() )
13967  return &(it->second);
13968  else
13969  return nullptr;
13970  }
13971 
13972  std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13973  std::string expandedTestSpec = unexpandedTestSpec;
13974  for( auto const& registryKvp : m_registry ) {
13975  std::size_t pos = expandedTestSpec.find( registryKvp.first );
13976  if( pos != std::string::npos ) {
13977  expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13978  registryKvp.second.tag +
13979  expandedTestSpec.substr( pos + registryKvp.first.size() );
13980  }
13981  }
13982  return expandedTestSpec;
13983  }
13984 
13985  void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
13986  CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
13987  "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
13988 
13989  CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
13990  "error: tag alias, '" << alias << "' already registered.\n"
13991  << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
13992  << "\tRedefined at: " << lineInfo );
13993  }
13994 
13995  ITagAliasRegistry::~ITagAliasRegistry() {}
13996 
13997  ITagAliasRegistry const& ITagAliasRegistry::get() {
13998  return getRegistryHub().getTagAliasRegistry();
13999  }
14000 
14001 } // end namespace Catch
14002 // end catch_tag_alias_registry.cpp
14003 // start catch_test_case_info.cpp
14004 
14005 #include <cctype>
14006 #include <exception>
14007 #include <algorithm>
14008 #include <sstream>
14009 
14010 namespace Catch {
14011 
14012  namespace {
14013  TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
14014  if( startsWith( tag, '.' ) ||
14015  tag == "!hide" )
14016  return TestCaseInfo::IsHidden;
14017  else if( tag == "!throws" )
14018  return TestCaseInfo::Throws;
14019  else if( tag == "!shouldfail" )
14020  return TestCaseInfo::ShouldFail;
14021  else if( tag == "!mayfail" )
14022  return TestCaseInfo::MayFail;
14023  else if( tag == "!nonportable" )
14024  return TestCaseInfo::NonPortable;
14025  else if( tag == "!benchmark" )
14026  return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14027  else
14028  return TestCaseInfo::None;
14029  }
14030  bool isReservedTag( std::string const& tag ) {
14031  return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14032  }
14033  void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
14034  CATCH_ENFORCE( !isReservedTag(tag),
14035  "Tag name: [" << tag << "] is not allowed.\n"
14036  << "Tag names starting with non alphanumeric characters are reserved\n"
14037  << _lineInfo );
14038  }
14039  }
14040 
14041  TestCase makeTestCase( ITestInvoker* _testCase,
14042  std::string const& _className,
14043  NameAndTags const& nameAndTags,
14044  SourceLineInfo const& _lineInfo )
14045  {
14046  bool isHidden = false;
14047 
14048  // Parse out tags
14049  std::vector<std::string> tags;
14050  std::string desc, tag;
14051  bool inTag = false;
14052  for (char c : nameAndTags.tags) {
14053  if( !inTag ) {
14054  if( c == '[' )
14055  inTag = true;
14056  else
14057  desc += c;
14058  }
14059  else {
14060  if( c == ']' ) {
14061  TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14062  if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14063  isHidden = true;
14064  else if( prop == TestCaseInfo::None )
14065  enforceNotReservedTag( tag, _lineInfo );
14066 
14067  // Merged hide tags like `[.approvals]` should be added as
14068  // `[.][approvals]`. The `[.]` is added at later point, so
14069  // we only strip the prefix
14070  if (startsWith(tag, '.') && tag.size() > 1) {
14071  tag.erase(0, 1);
14072  }
14073  tags.push_back( tag );
14074  tag.clear();
14075  inTag = false;
14076  }
14077  else
14078  tag += c;
14079  }
14080  }
14081  if( isHidden ) {
14082  // Add all "hidden" tags to make them behave identically
14083  tags.insert( tags.end(), { ".", "!hide" } );
14084  }
14085 
14086  TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14087  return TestCase( _testCase, std::move(info) );
14088  }
14089 
14090  void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14091  std::sort(begin(tags), end(tags));
14092  tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14093  testCaseInfo.lcaseTags.clear();
14094 
14095  for( auto const& tag : tags ) {
14096  std::string lcaseTag = toLower( tag );
14097  testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14098  testCaseInfo.lcaseTags.push_back( lcaseTag );
14099  }
14100  testCaseInfo.tags = std::move(tags);
14101  }
14102 
14103  TestCaseInfo::TestCaseInfo( std::string const& _name,
14104  std::string const& _className,
14105  std::string const& _description,
14106  std::vector<std::string> const& _tags,
14107  SourceLineInfo const& _lineInfo )
14108  : name( _name ),
14109  className( _className ),
14110  description( _description ),
14111  lineInfo( _lineInfo ),
14112  properties( None )
14113  {
14114  setTags( *this, _tags );
14115  }
14116 
14117  bool TestCaseInfo::isHidden() const {
14118  return ( properties & IsHidden ) != 0;
14119  }
14120  bool TestCaseInfo::throws() const {
14121  return ( properties & Throws ) != 0;
14122  }
14123  bool TestCaseInfo::okToFail() const {
14124  return ( properties & (ShouldFail | MayFail ) ) != 0;
14125  }
14126  bool TestCaseInfo::expectedToFail() const {
14127  return ( properties & (ShouldFail ) ) != 0;
14128  }
14129 
14130  std::string TestCaseInfo::tagsAsString() const {
14131  std::string ret;
14132  // '[' and ']' per tag
14133  std::size_t full_size = 2 * tags.size();
14134  for (const auto& tag : tags) {
14135  full_size += tag.size();
14136  }
14137  ret.reserve(full_size);
14138  for (const auto& tag : tags) {
14139  ret.push_back('[');
14140  ret.append(tag);
14141  ret.push_back(']');
14142  }
14143 
14144  return ret;
14145  }
14146 
14147  TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14148 
14149  TestCase TestCase::withName( std::string const& _newName ) const {
14150  TestCase other( *this );
14151  other.name = _newName;
14152  return other;
14153  }
14154 
14155  void TestCase::invoke() const {
14156  test->invoke();
14157  }
14158 
14159  bool TestCase::operator == ( TestCase const& other ) const {
14160  return test.get() == other.test.get() &&
14161  name == other.name &&
14162  className == other.className;
14163  }
14164 
14165  bool TestCase::operator < ( TestCase const& other ) const {
14166  return name < other.name;
14167  }
14168 
14169  TestCaseInfo const& TestCase::getTestCaseInfo() const
14170  {
14171  return *this;
14172  }
14173 
14174 } // end namespace Catch
14175 // end catch_test_case_info.cpp
14176 // start catch_test_case_registry_impl.cpp
14177 
14178 #include <algorithm>
14179 #include <sstream>
14180 
14181 namespace Catch {
14182 
14183  namespace {
14184  struct TestHasher {
14185  using hash_t = uint64_t;
14186 
14187  explicit TestHasher( hash_t hashSuffix ):
14188  m_hashSuffix{ hashSuffix } {}
14189 
14190  uint32_t operator()( TestCase const& t ) const {
14191  // FNV-1a hash with multiplication fold.
14192  const hash_t prime = 1099511628211u;
14193  hash_t hash = 14695981039346656037u;
14194  for ( const char c : t.name ) {
14195  hash ^= c;
14196  hash *= prime;
14197  }
14198  hash ^= m_hashSuffix;
14199  hash *= prime;
14200  const uint32_t low{ static_cast<uint32_t>( hash ) };
14201  const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
14202  return low * high;
14203  }
14204 
14205  private:
14206  hash_t m_hashSuffix;
14207  };
14208  } // end unnamed namespace
14209 
14210  std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
14211  switch( config.runOrder() ) {
14212  case RunTests::InDeclarationOrder:
14213  // already in declaration order
14214  break;
14215 
14216  case RunTests::InLexicographicalOrder: {
14217  std::vector<TestCase> sorted = unsortedTestCases;
14218  std::sort( sorted.begin(), sorted.end() );
14219  return sorted;
14220  }
14221 
14222  case RunTests::InRandomOrder: {
14223  seedRng( config );
14224  TestHasher h{ config.rngSeed() };
14225 
14226  using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14227  std::vector<hashedTest> indexed_tests;
14228  indexed_tests.reserve( unsortedTestCases.size() );
14229 
14230  for (auto const& testCase : unsortedTestCases) {
14231  indexed_tests.emplace_back(h(testCase), &testCase);
14232  }
14233 
14234  std::sort(indexed_tests.begin(), indexed_tests.end(),
14235  [](hashedTest const& lhs, hashedTest const& rhs) {
14236  if (lhs.first == rhs.first) {
14237  return lhs.second->name < rhs.second->name;
14238  }
14239  return lhs.first < rhs.first;
14240  });
14241 
14242  std::vector<TestCase> sorted;
14243  sorted.reserve( indexed_tests.size() );
14244 
14245  for (auto const& hashed : indexed_tests) {
14246  sorted.emplace_back(*hashed.second);
14247  }
14248 
14249  return sorted;
14250  }
14251  }
14252  return unsortedTestCases;
14253  }
14254 
14255  bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
14256  return !testCase.throws() || config.allowThrows();
14257  }
14258 
14259  bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
14260  return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14261  }
14262 
14263  void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
14264  std::set<TestCase> seenFunctions;
14265  for( auto const& function : functions ) {
14266  auto prev = seenFunctions.insert( function );
14267  CATCH_ENFORCE( prev.second,
14268  "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14269  << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
14270  << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
14271  }
14272  }
14273 
14274  std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
14275  std::vector<TestCase> filtered;
14276  filtered.reserve( testCases.size() );
14277  for (auto const& testCase : testCases) {
14278  if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14279  (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14280  filtered.push_back(testCase);
14281  }
14282  }
14283  return filtered;
14284  }
14285  std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
14286  return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14287  }
14288 
14289  void TestRegistry::registerTest( TestCase const& testCase ) {
14290  std::string name = testCase.getTestCaseInfo().name;
14291  if( name.empty() ) {
14293  rss << "Anonymous test case " << ++m_unnamedCount;
14294  return registerTest( testCase.withName( rss.str() ) );
14295  }
14296  m_functions.push_back( testCase );
14297  }
14298 
14299  std::vector<TestCase> const& TestRegistry::getAllTests() const {
14300  return m_functions;
14301  }
14302  std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
14303  if( m_sortedFunctions.empty() )
14304  enforceNoDuplicateTestCases( m_functions );
14305 
14306  if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14307  m_sortedFunctions = sortTests( config, m_functions );
14308  m_currentSortOrder = config.runOrder();
14309  }
14310  return m_sortedFunctions;
14311  }
14312 
14314  TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14315 
14316  void TestInvokerAsFunction::invoke() const {
14317  m_testAsFunction();
14318  }
14319 
14320  std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
14321  std::string className(classOrQualifiedMethodName);
14322  if( startsWith( className, '&' ) )
14323  {
14324  std::size_t lastColons = className.rfind( "::" );
14325  std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
14326  if( penultimateColons == std::string::npos )
14327  penultimateColons = 1;
14328  className = className.substr( penultimateColons, lastColons-penultimateColons );
14329  }
14330  return className;
14331  }
14332 
14333 } // end namespace Catch
14334 // end catch_test_case_registry_impl.cpp
14335 // start catch_test_case_tracker.cpp
14336 
14337 #include <algorithm>
14338 #include <cassert>
14339 #include <stdexcept>
14340 #include <memory>
14341 #include <sstream>
14342 
14343 #if defined(__clang__)
14344 # pragma clang diagnostic push
14345 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14346 #endif
14347 
14348 namespace Catch {
14349 namespace TestCaseTracking {
14350 
14351  NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
14352  : name( _name ),
14353  location( _location )
14354  {}
14355 
14356  ITracker::~ITracker() = default;
14357 
14358  ITracker& TrackerContext::startRun() {
14359  m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
14360  m_currentTracker = nullptr;
14361  m_runState = Executing;
14362  return *m_rootTracker;
14363  }
14364 
14365  void TrackerContext::endRun() {
14366  m_rootTracker.reset();
14367  m_currentTracker = nullptr;
14368  m_runState = NotStarted;
14369  }
14370 
14371  void TrackerContext::startCycle() {
14372  m_currentTracker = m_rootTracker.get();
14373  m_runState = Executing;
14374  }
14375  void TrackerContext::completeCycle() {
14376  m_runState = CompletedCycle;
14377  }
14378 
14379  bool TrackerContext::completedCycle() const {
14380  return m_runState == CompletedCycle;
14381  }
14382  ITracker& TrackerContext::currentTracker() {
14383  return *m_currentTracker;
14384  }
14385  void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14386  m_currentTracker = tracker;
14387  }
14388 
14389  TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14390  ITracker(nameAndLocation),
14391  m_ctx( ctx ),
14392  m_parent( parent )
14393  {}
14394 
14395  bool TrackerBase::isComplete() const {
14396  return m_runState == CompletedSuccessfully || m_runState == Failed;
14397  }
14398  bool TrackerBase::isSuccessfullyCompleted() const {
14399  return m_runState == CompletedSuccessfully;
14400  }
14401  bool TrackerBase::isOpen() const {
14402  return m_runState != NotStarted && !isComplete();
14403  }
14404  bool TrackerBase::hasChildren() const {
14405  return !m_children.empty();
14406  }
14407 
14408  void TrackerBase::addChild( ITrackerPtr const& child ) {
14409  m_children.push_back( child );
14410  }
14411 
14412  ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
14413  auto it = std::find_if( m_children.begin(), m_children.end(),
14414  [&nameAndLocation]( ITrackerPtr const& tracker ){
14415  return
14416  tracker->nameAndLocation().location == nameAndLocation.location &&
14417  tracker->nameAndLocation().name == nameAndLocation.name;
14418  } );
14419  return( it != m_children.end() )
14420  ? *it
14421  : nullptr;
14422  }
14423  ITracker& TrackerBase::parent() {
14424  assert( m_parent ); // Should always be non-null except for root
14425  return *m_parent;
14426  }
14427 
14428  void TrackerBase::openChild() {
14429  if( m_runState != ExecutingChildren ) {
14430  m_runState = ExecutingChildren;
14431  if( m_parent )
14432  m_parent->openChild();
14433  }
14434  }
14435 
14436  bool TrackerBase::isSectionTracker() const { return false; }
14437  bool TrackerBase::isGeneratorTracker() const { return false; }
14438 
14439  void TrackerBase::open() {
14440  m_runState = Executing;
14441  moveToThis();
14442  if( m_parent )
14443  m_parent->openChild();
14444  }
14445 
14446  void TrackerBase::close() {
14447 
14448  // Close any still open children (e.g. generators)
14449  while( &m_ctx.currentTracker() != this )
14450  m_ctx.currentTracker().close();
14451 
14452  switch( m_runState ) {
14453  case NeedsAnotherRun:
14454  break;
14455 
14456  case Executing:
14457  m_runState = CompletedSuccessfully;
14458  break;
14459  case ExecutingChildren:
14460  if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
14461  m_runState = CompletedSuccessfully;
14462  break;
14463 
14464  case NotStarted:
14465  case CompletedSuccessfully:
14466  case Failed:
14467  CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
14468 
14469  default:
14470  CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
14471  }
14472  moveToParent();
14473  m_ctx.completeCycle();
14474  }
14475  void TrackerBase::fail() {
14476  m_runState = Failed;
14477  if( m_parent )
14478  m_parent->markAsNeedingAnotherRun();
14479  moveToParent();
14480  m_ctx.completeCycle();
14481  }
14482  void TrackerBase::markAsNeedingAnotherRun() {
14483  m_runState = NeedsAnotherRun;
14484  }
14485 
14486  void TrackerBase::moveToParent() {
14487  assert( m_parent );
14488  m_ctx.setCurrentTracker( m_parent );
14489  }
14490  void TrackerBase::moveToThis() {
14491  m_ctx.setCurrentTracker( this );
14492  }
14493 
14494  SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14495  : TrackerBase( nameAndLocation, ctx, parent ),
14496  m_trimmed_name(trim(nameAndLocation.name))
14497  {
14498  if( parent ) {
14499  while( !parent->isSectionTracker() )
14500  parent = &parent->parent();
14501 
14502  SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
14503  addNextFilters( parentSection.m_filters );
14504  }
14505  }
14506 
14507  bool SectionTracker::isComplete() const {
14508  bool complete = true;
14509 
14510  if (m_filters.empty()
14511  || m_filters[0] == ""
14512  || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14513  complete = TrackerBase::isComplete();
14514  }
14515  return complete;
14516  }
14517 
14518  bool SectionTracker::isSectionTracker() const { return true; }
14519 
14520  SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
14521  std::shared_ptr<SectionTracker> section;
14522 
14523  ITracker& currentTracker = ctx.currentTracker();
14524  if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14525  assert( childTracker );
14526  assert( childTracker->isSectionTracker() );
14527  section = std::static_pointer_cast<SectionTracker>( childTracker );
14528  }
14529  else {
14530  section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
14531  currentTracker.addChild( section );
14532  }
14533  if( !ctx.completedCycle() )
14534  section->tryOpen();
14535  return *section;
14536  }
14537 
14538  void SectionTracker::tryOpen() {
14539  if( !isComplete() )
14540  open();
14541  }
14542 
14543  void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
14544  if( !filters.empty() ) {
14545  m_filters.reserve( m_filters.size() + filters.size() + 2 );
14546  m_filters.emplace_back(""); // Root - should never be consulted
14547  m_filters.emplace_back(""); // Test Case - not a section filter
14548  m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14549  }
14550  }
14551  void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
14552  if( filters.size() > 1 )
14553  m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14554  }
14555 
14556  std::vector<std::string> const& SectionTracker::getFilters() const {
14557  return m_filters;
14558  }
14559 
14560  std::string const& SectionTracker::trimmedName() const {
14561  return m_trimmed_name;
14562  }
14563 
14564 } // namespace TestCaseTracking
14565 
14566 using TestCaseTracking::ITracker;
14567 using TestCaseTracking::TrackerContext;
14568 using TestCaseTracking::SectionTracker;
14569 
14570 } // namespace Catch
14571 
14572 #if defined(__clang__)
14573 # pragma clang diagnostic pop
14574 #endif
14575 // end catch_test_case_tracker.cpp
14576 // start catch_test_registry.cpp
14577 
14578 namespace Catch {
14579 
14580  auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14581  return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14582  }
14583 
14584  NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14585 
14586  AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
14587  CATCH_TRY {
14588  getMutableRegistryHub()
14589  .registerTest(
14590  makeTestCase(
14591  invoker,
14592  extractClassName( classOrMethod ),
14593  nameAndTags,
14594  lineInfo));
14595  } CATCH_CATCH_ALL {
14596  // Do not throw when constructing global objects, instead register the exception to be processed later
14597  getMutableRegistryHub().registerStartupException();
14598  }
14599  }
14600 
14601  AutoReg::~AutoReg() = default;
14602 }
14603 // end catch_test_registry.cpp
14604 // start catch_test_spec.cpp
14605 
14606 #include <algorithm>
14607 #include <string>
14608 #include <vector>
14609 #include <memory>
14610 
14611 namespace Catch {
14612 
14613  TestSpec::Pattern::Pattern( std::string const& name )
14614  : m_name( name )
14615  {}
14616 
14617  TestSpec::Pattern::~Pattern() = default;
14618 
14619  std::string const& TestSpec::Pattern::name() const {
14620  return m_name;
14621  }
14622 
14623  TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14624  : Pattern( filterString )
14625  , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14626  {}
14627 
14628  bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14629  return m_wildcardPattern.matches( testCase.name );
14630  }
14631 
14632  TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14633  : Pattern( filterString )
14634  , m_tag( toLower( tag ) )
14635  {}
14636 
14637  bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14638  return std::find(begin(testCase.lcaseTags),
14639  end(testCase.lcaseTags),
14640  m_tag) != end(testCase.lcaseTags);
14641  }
14642 
14643  TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14644  : Pattern( underlyingPattern->name() )
14645  , m_underlyingPattern( underlyingPattern )
14646  {}
14647 
14648  bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14649  return !m_underlyingPattern->matches( testCase );
14650  }
14651 
14652  bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14653  return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14654  }
14655 
14656  std::string TestSpec::Filter::name() const {
14657  std::string name;
14658  for( auto const& p : m_patterns )
14659  name += p->name();
14660  return name;
14661  }
14662 
14663  bool TestSpec::hasFilters() const {
14664  return !m_filters.empty();
14665  }
14666 
14667  bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14668  return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14669  }
14670 
14671  TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14672  {
14673  Matches matches( m_filters.size() );
14674  std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14675  std::vector<TestCase const*> currentMatches;
14676  for( auto const& test : testCases )
14677  if( isThrowSafe( test, config ) && filter.matches( test ) )
14678  currentMatches.emplace_back( &test );
14679  return FilterMatch{ filter.name(), currentMatches };
14680  } );
14681  return matches;
14682  }
14683 
14684  const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
14685  return (m_invalidArgs);
14686  }
14687 
14688 }
14689 // end catch_test_spec.cpp
14690 // start catch_test_spec_parser.cpp
14691 
14692 namespace Catch {
14693 
14694  TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14695 
14696  TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14697  m_mode = None;
14698  m_exclusion = false;
14699  m_arg = m_tagAliases->expandAliases( arg );
14700  m_escapeChars.clear();
14701  m_substring.reserve(m_arg.size());
14702  m_patternName.reserve(m_arg.size());
14703  m_realPatternPos = 0;
14704 
14705  for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14706  //if visitChar fails
14707  if( !visitChar( m_arg[m_pos] ) ){
14708  m_testSpec.m_invalidArgs.push_back(arg);
14709  break;
14710  }
14711  endMode();
14712  return *this;
14713  }
14714  TestSpec TestSpecParser::testSpec() {
14715  addFilter();
14716  return m_testSpec;
14717  }
14718  bool TestSpecParser::visitChar( char c ) {
14719  if( (m_mode != EscapedName) && (c == '\\') ) {
14720  escape();
14721  addCharToPattern(c);
14722  return true;
14723  }else if((m_mode != EscapedName) && (c == ',') ) {
14724  return separate();
14725  }
14726 
14727  switch( m_mode ) {
14728  case None:
14729  if( processNoneChar( c ) )
14730  return true;
14731  break;
14732  case Name:
14733  processNameChar( c );
14734  break;
14735  case EscapedName:
14736  endMode();
14737  addCharToPattern(c);
14738  return true;
14739  default:
14740  case Tag:
14741  case QuotedName:
14742  if( processOtherChar( c ) )
14743  return true;
14744  break;
14745  }
14746 
14747  m_substring += c;
14748  if( !isControlChar( c ) ) {
14749  m_patternName += c;
14750  m_realPatternPos++;
14751  }
14752  return true;
14753  }
14754  // Two of the processing methods return true to signal the caller to return
14755  // without adding the given character to the current pattern strings
14756  bool TestSpecParser::processNoneChar( char c ) {
14757  switch( c ) {
14758  case ' ':
14759  return true;
14760  case '~':
14761  m_exclusion = true;
14762  return false;
14763  case '[':
14764  startNewMode( Tag );
14765  return false;
14766  case '"':
14767  startNewMode( QuotedName );
14768  return false;
14769  default:
14770  startNewMode( Name );
14771  return false;
14772  }
14773  }
14774  void TestSpecParser::processNameChar( char c ) {
14775  if( c == '[' ) {
14776  if( m_substring == "exclude:" )
14777  m_exclusion = true;
14778  else
14779  endMode();
14780  startNewMode( Tag );
14781  }
14782  }
14783  bool TestSpecParser::processOtherChar( char c ) {
14784  if( !isControlChar( c ) )
14785  return false;
14786  m_substring += c;
14787  endMode();
14788  return true;
14789  }
14790  void TestSpecParser::startNewMode( Mode mode ) {
14791  m_mode = mode;
14792  }
14793  void TestSpecParser::endMode() {
14794  switch( m_mode ) {
14795  case Name:
14796  case QuotedName:
14797  return addNamePattern();
14798  case Tag:
14799  return addTagPattern();
14800  case EscapedName:
14801  revertBackToLastMode();
14802  return;
14803  case None:
14804  default:
14805  return startNewMode( None );
14806  }
14807  }
14808  void TestSpecParser::escape() {
14809  saveLastMode();
14810  m_mode = EscapedName;
14811  m_escapeChars.push_back(m_realPatternPos);
14812  }
14813  bool TestSpecParser::isControlChar( char c ) const {
14814  switch( m_mode ) {
14815  default:
14816  return false;
14817  case None:
14818  return c == '~';
14819  case Name:
14820  return c == '[';
14821  case EscapedName:
14822  return true;
14823  case QuotedName:
14824  return c == '"';
14825  case Tag:
14826  return c == '[' || c == ']';
14827  }
14828  }
14829 
14830  void TestSpecParser::addFilter() {
14831  if( !m_currentFilter.m_patterns.empty() ) {
14832  m_testSpec.m_filters.push_back( m_currentFilter );
14833  m_currentFilter = TestSpec::Filter();
14834  }
14835  }
14836 
14837  void TestSpecParser::saveLastMode() {
14838  lastMode = m_mode;
14839  }
14840 
14841  void TestSpecParser::revertBackToLastMode() {
14842  m_mode = lastMode;
14843  }
14844 
14845  bool TestSpecParser::separate() {
14846  if( (m_mode==QuotedName) || (m_mode==Tag) ){
14847  //invalid argument, signal failure to previous scope.
14848  m_mode = None;
14849  m_pos = m_arg.size();
14850  m_substring.clear();
14851  m_patternName.clear();
14852  m_realPatternPos = 0;
14853  return false;
14854  }
14855  endMode();
14856  addFilter();
14857  return true; //success
14858  }
14859 
14860  std::string TestSpecParser::preprocessPattern() {
14861  std::string token = m_patternName;
14862  for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14863  token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14864  m_escapeChars.clear();
14865  if (startsWith(token, "exclude:")) {
14866  m_exclusion = true;
14867  token = token.substr(8);
14868  }
14869 
14870  m_patternName.clear();
14871  m_realPatternPos = 0;
14872 
14873  return token;
14874  }
14875 
14876  void TestSpecParser::addNamePattern() {
14877  auto token = preprocessPattern();
14878 
14879  if (!token.empty()) {
14880  TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14881  if (m_exclusion)
14882  pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14883  m_currentFilter.m_patterns.push_back(pattern);
14884  }
14885  m_substring.clear();
14886  m_exclusion = false;
14887  m_mode = None;
14888  }
14889 
14890  void TestSpecParser::addTagPattern() {
14891  auto token = preprocessPattern();
14892 
14893  if (!token.empty()) {
14894  // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14895  // we have to create a separate hide tag and shorten the real one
14896  if (token.size() > 1 && token[0] == '.') {
14897  token.erase(token.begin());
14898  TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14899  if (m_exclusion) {
14900  pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14901  }
14902  m_currentFilter.m_patterns.push_back(pattern);
14903  }
14904 
14905  TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14906 
14907  if (m_exclusion) {
14908  pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14909  }
14910  m_currentFilter.m_patterns.push_back(pattern);
14911  }
14912  m_substring.clear();
14913  m_exclusion = false;
14914  m_mode = None;
14915  }
14916 
14917  TestSpec parseTestSpec( std::string const& arg ) {
14918  return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14919  }
14920 
14921 } // namespace Catch
14922 // end catch_test_spec_parser.cpp
14923 // start catch_timer.cpp
14924 
14925 #include <chrono>
14926 
14927 static const uint64_t nanosecondsInSecond = 1000000000;
14928 
14929 namespace Catch {
14930 
14931  auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14932  return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14933  }
14934 
14935  namespace {
14936  auto estimateClockResolution() -> uint64_t {
14937  uint64_t sum = 0;
14938  static const uint64_t iterations = 1000000;
14939 
14940  auto startTime = getCurrentNanosecondsSinceEpoch();
14941 
14942  for( std::size_t i = 0; i < iterations; ++i ) {
14943 
14944  uint64_t ticks;
14945  uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14946  do {
14947  ticks = getCurrentNanosecondsSinceEpoch();
14948  } while( ticks == baseTicks );
14949 
14950  auto delta = ticks - baseTicks;
14951  sum += delta;
14952 
14953  // If we have been calibrating for over 3 seconds -- the clock
14954  // is terrible and we should move on.
14955  // TBD: How to signal that the measured resolution is probably wrong?
14956  if (ticks > startTime + 3 * nanosecondsInSecond) {
14957  return sum / ( i + 1u );
14958  }
14959  }
14960 
14961  // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14962  // - and potentially do more iterations if there's a high variance.
14963  return sum/iterations;
14964  }
14965  }
14966  auto getEstimatedClockResolution() -> uint64_t {
14967  static auto s_resolution = estimateClockResolution();
14968  return s_resolution;
14969  }
14970 
14971  void Timer::start() {
14972  m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14973  }
14974  auto Timer::getElapsedNanoseconds() const -> uint64_t {
14975  return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14976  }
14977  auto Timer::getElapsedMicroseconds() const -> uint64_t {
14978  return getElapsedNanoseconds()/1000;
14979  }
14980  auto Timer::getElapsedMilliseconds() const -> unsigned int {
14981  return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14982  }
14983  auto Timer::getElapsedSeconds() const -> double {
14984  return getElapsedMicroseconds()/1000000.0;
14985  }
14986 
14987 } // namespace Catch
14988 // end catch_timer.cpp
14989 // start catch_tostring.cpp
14990 
14991 #if defined(__clang__)
14992 # pragma clang diagnostic push
14993 # pragma clang diagnostic ignored "-Wexit-time-destructors"
14994 # pragma clang diagnostic ignored "-Wglobal-constructors"
14995 #endif
14996 
14997 // Enable specific decls locally
14998 #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
14999 #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15000 #endif
15001 
15002 #include <cmath>
15003 #include <iomanip>
15004 
15005 namespace Catch {
15006 
15007 namespace Detail {
15008 
15009  const std::string unprintableString = "{?}";
15010 
15011  namespace {
15012  const int hexThreshold = 255;
15013 
15014  struct Endianness {
15015  enum Arch { Big, Little };
15016 
15017  static Arch which() {
15018  int one = 1;
15019  // If the lowest byte we read is non-zero, we can assume
15020  // that little endian format is used.
15021  auto value = *reinterpret_cast<char*>(&one);
15022  return value ? Little : Big;
15023  }
15024  };
15025  }
15026 
15027  std::string rawMemoryToString( const void *object, std::size_t size ) {
15028  // Reverse order for little endian architectures
15029  int i = 0, end = static_cast<int>( size ), inc = 1;
15030  if( Endianness::which() == Endianness::Little ) {
15031  i = end-1;
15032  end = inc = -1;
15033  }
15034 
15035  unsigned char const *bytes = static_cast<unsigned char const *>(object);
15037  rss << "0x" << std::setfill('0') << std::hex;
15038  for( ; i != end; i += inc )
15039  rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15040  return rss.str();
15041  }
15042 }
15043 
15044 template<typename T>
15045 std::string fpToString( T value, int precision ) {
15046  if (Catch::isnan(value)) {
15047  return "nan";
15048  }
15049 
15051  rss << std::setprecision( precision )
15052  << std::fixed
15053  << value;
15054  std::string d = rss.str();
15055  std::size_t i = d.find_last_not_of( '0' );
15056  if( i != std::string::npos && i != d.size()-1 ) {
15057  if( d[i] == '.' )
15058  i++;
15059  d = d.substr( 0, i+1 );
15060  }
15061  return d;
15062 }
15063 
15065 //
15066 // Out-of-line defs for full specialization of StringMaker
15067 //
15069 
15070 std::string StringMaker<std::string>::convert(const std::string& str) {
15071  if (!getCurrentContext().getConfig()->showInvisibles()) {
15072  return '"' + str + '"';
15073  }
15074 
15075  std::string s("\"");
15076  for (char c : str) {
15077  switch (c) {
15078  case '\n':
15079  s.append("\\n");
15080  break;
15081  case '\t':
15082  s.append("\\t");
15083  break;
15084  default:
15085  s.push_back(c);
15086  break;
15087  }
15088  }
15089  s.append("\"");
15090  return s;
15091 }
15092 
15093 #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15094 std::string StringMaker<std::string_view>::convert(std::string_view str) {
15095  return ::Catch::Detail::stringify(std::string{ str });
15096 }
15097 #endif
15098 
15099 std::string StringMaker<char const*>::convert(char const* str) {
15100  if (str) {
15101  return ::Catch::Detail::stringify(std::string{ str });
15102  } else {
15103  return{ "{null string}" };
15104  }
15105 }
15106 std::string StringMaker<char*>::convert(char* str) {
15107  if (str) {
15108  return ::Catch::Detail::stringify(std::string{ str });
15109  } else {
15110  return{ "{null string}" };
15111  }
15112 }
15113 
15114 #ifdef CATCH_CONFIG_WCHAR
15115 std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15116  std::string s;
15117  s.reserve(wstr.size());
15118  for (auto c : wstr) {
15119  s += (c <= 0xff) ? static_cast<char>(c) : '?';
15120  }
15121  return ::Catch::Detail::stringify(s);
15122 }
15123 
15124 # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15125 std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15126  return StringMaker<std::wstring>::convert(std::wstring(str));
15127 }
15128 # endif
15129 
15130 std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
15131  if (str) {
15132  return ::Catch::Detail::stringify(std::wstring{ str });
15133  } else {
15134  return{ "{null string}" };
15135  }
15136 }
15137 std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
15138  if (str) {
15139  return ::Catch::Detail::stringify(std::wstring{ str });
15140  } else {
15141  return{ "{null string}" };
15142  }
15143 }
15144 #endif
15145 
15146 #if defined(CATCH_CONFIG_CPP17_BYTE)
15147 #include <cstddef>
15148 std::string StringMaker<std::byte>::convert(std::byte value) {
15149  return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15150 }
15151 #endif // defined(CATCH_CONFIG_CPP17_BYTE)
15152 
15153 std::string StringMaker<int>::convert(int value) {
15154  return ::Catch::Detail::stringify(static_cast<long long>(value));
15155 }
15156 std::string StringMaker<long>::convert(long value) {
15157  return ::Catch::Detail::stringify(static_cast<long long>(value));
15158 }
15159 std::string StringMaker<long long>::convert(long long value) {
15161  rss << value;
15162  if (value > Detail::hexThreshold) {
15163  rss << " (0x" << std::hex << value << ')';
15164  }
15165  return rss.str();
15166 }
15167 
15168 std::string StringMaker<unsigned int>::convert(unsigned int value) {
15169  return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15170 }
15171 std::string StringMaker<unsigned long>::convert(unsigned long value) {
15172  return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15173 }
15174 std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15176  rss << value;
15177  if (value > Detail::hexThreshold) {
15178  rss << " (0x" << std::hex << value << ')';
15179  }
15180  return rss.str();
15181 }
15182 
15183 std::string StringMaker<bool>::convert(bool b) {
15184  return b ? "true" : "false";
15185 }
15186 
15187 std::string StringMaker<signed char>::convert(signed char value) {
15188  if (value == '\r') {
15189  return "'\\r'";
15190  } else if (value == '\f') {
15191  return "'\\f'";
15192  } else if (value == '\n') {
15193  return "'\\n'";
15194  } else if (value == '\t') {
15195  return "'\\t'";
15196  } else if ('\0' <= value && value < ' ') {
15197  return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15198  } else {
15199  char chstr[] = "' '";
15200  chstr[1] = value;
15201  return chstr;
15202  }
15203 }
15204 std::string StringMaker<char>::convert(char c) {
15205  return ::Catch::Detail::stringify(static_cast<signed char>(c));
15206 }
15207 std::string StringMaker<unsigned char>::convert(unsigned char c) {
15208  return ::Catch::Detail::stringify(static_cast<char>(c));
15209 }
15210 
15211 std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15212  return "nullptr";
15213 }
15214 
15216 
15217 std::string StringMaker<float>::convert(float value) {
15218  return fpToString(value, precision) + 'f';
15219 }
15220 
15222 
15223 std::string StringMaker<double>::convert(double value) {
15224  return fpToString(value, precision);
15225 }
15226 
15227 std::string ratio_string<std::atto>::symbol() { return "a"; }
15228 std::string ratio_string<std::femto>::symbol() { return "f"; }
15229 std::string ratio_string<std::pico>::symbol() { return "p"; }
15230 std::string ratio_string<std::nano>::symbol() { return "n"; }
15231 std::string ratio_string<std::micro>::symbol() { return "u"; }
15232 std::string ratio_string<std::milli>::symbol() { return "m"; }
15233 
15234 } // end namespace Catch
15235 
15236 #if defined(__clang__)
15237 # pragma clang diagnostic pop
15238 #endif
15239 
15240 // end catch_tostring.cpp
15241 // start catch_totals.cpp
15242 
15243 namespace Catch {
15244 
15245  Counts Counts::operator - ( Counts const& other ) const {
15246  Counts diff;
15247  diff.passed = passed - other.passed;
15248  diff.failed = failed - other.failed;
15249  diff.failedButOk = failedButOk - other.failedButOk;
15250  return diff;
15251  }
15252 
15253  Counts& Counts::operator += ( Counts const& other ) {
15254  passed += other.passed;
15255  failed += other.failed;
15256  failedButOk += other.failedButOk;
15257  return *this;
15258  }
15259 
15260  std::size_t Counts::total() const {
15261  return passed + failed + failedButOk;
15262  }
15263  bool Counts::allPassed() const {
15264  return failed == 0 && failedButOk == 0;
15265  }
15266  bool Counts::allOk() const {
15267  return failed == 0;
15268  }
15269 
15270  Totals Totals::operator - ( Totals const& other ) const {
15271  Totals diff;
15272  diff.assertions = assertions - other.assertions;
15273  diff.testCases = testCases - other.testCases;
15274  return diff;
15275  }
15276 
15277  Totals& Totals::operator += ( Totals const& other ) {
15278  assertions += other.assertions;
15279  testCases += other.testCases;
15280  return *this;
15281  }
15282 
15283  Totals Totals::delta( Totals const& prevTotals ) const {
15284  Totals diff = *this - prevTotals;
15285  if( diff.assertions.failed > 0 )
15286  ++diff.testCases.failed;
15287  else if( diff.assertions.failedButOk > 0 )
15288  ++diff.testCases.failedButOk;
15289  else
15290  ++diff.testCases.passed;
15291  return diff;
15292  }
15293 
15294 }
15295 // end catch_totals.cpp
15296 // start catch_uncaught_exceptions.cpp
15297 
15298 // start catch_config_uncaught_exceptions.hpp
15299 
15300 // Copyright Catch2 Authors
15301 // Distributed under the Boost Software License, Version 1.0.
15302 // (See accompanying file LICENSE_1_0.txt or copy at
15303 // https://www.boost.org/LICENSE_1_0.txt)
15304 
15305 // SPDX-License-Identifier: BSL-1.0
15306 
15307 #ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15308 #define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15309 
15310 #if defined(_MSC_VER)
15311 # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15312 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15313 # endif
15314 #endif
15315 
15316 #include <exception>
15317 
15318 #if defined(__cpp_lib_uncaught_exceptions) \
15319  && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15320 
15321 # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15322 #endif // __cpp_lib_uncaught_exceptions
15323 
15324 #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15325  && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15326  && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15327 
15328 # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15329 #endif
15330 
15331 #endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15332 // end catch_config_uncaught_exceptions.hpp
15333 #include <exception>
15334 
15335 namespace Catch {
15336  bool uncaught_exceptions() {
15337 #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15338  return false;
15339 #elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15340  return std::uncaught_exceptions() > 0;
15341 #else
15342  return std::uncaught_exception();
15343 #endif
15344  }
15345 } // end namespace Catch
15346 // end catch_uncaught_exceptions.cpp
15347 // start catch_version.cpp
15348 
15349 #include <ostream>
15350 
15351 namespace Catch {
15352 
15353  Version::Version
15354  ( unsigned int _majorVersion,
15355  unsigned int _minorVersion,
15356  unsigned int _patchNumber,
15357  char const * const _branchName,
15358  unsigned int _buildNumber )
15359  : majorVersion( _majorVersion ),
15360  minorVersion( _minorVersion ),
15361  patchNumber( _patchNumber ),
15362  branchName( _branchName ),
15363  buildNumber( _buildNumber )
15364  {}
15365 
15366  std::ostream& operator << ( std::ostream& os, Version const& version ) {
15367  os << version.majorVersion << '.'
15368  << version.minorVersion << '.'
15369  << version.patchNumber;
15370  // branchName is never null -> 0th char is \0 if it is empty
15371  if (version.branchName[0]) {
15372  os << '-' << version.branchName
15373  << '.' << version.buildNumber;
15374  }
15375  return os;
15376  }
15377 
15378  Version const& libraryVersion() {
15379  static Version version( 2, 13, 6, "", 0 );
15380  return version;
15381  }
15382 
15383 }
15384 // end catch_version.cpp
15385 // start catch_wildcard_pattern.cpp
15386 
15387 namespace Catch {
15388 
15389  WildcardPattern::WildcardPattern( std::string const& pattern,
15390  CaseSensitive::Choice caseSensitivity )
15391  : m_caseSensitivity( caseSensitivity ),
15392  m_pattern( normaliseString( pattern ) )
15393  {
15394  if( startsWith( m_pattern, '*' ) ) {
15395  m_pattern = m_pattern.substr( 1 );
15396  m_wildcard = WildcardAtStart;
15397  }
15398  if( endsWith( m_pattern, '*' ) ) {
15399  m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15400  m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
15401  }
15402  }
15403 
15404  bool WildcardPattern::matches( std::string const& str ) const {
15405  switch( m_wildcard ) {
15406  case NoWildcard:
15407  return m_pattern == normaliseString( str );
15408  case WildcardAtStart:
15409  return endsWith( normaliseString( str ), m_pattern );
15410  case WildcardAtEnd:
15411  return startsWith( normaliseString( str ), m_pattern );
15412  case WildcardAtBothEnds:
15413  return contains( normaliseString( str ), m_pattern );
15414  default:
15415  CATCH_INTERNAL_ERROR( "Unknown enum" );
15416  }
15417  }
15418 
15419  std::string WildcardPattern::normaliseString( std::string const& str ) const {
15420  return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15421  }
15422 }
15423 // end catch_wildcard_pattern.cpp
15424 // start catch_xmlwriter.cpp
15425 
15426 #include <iomanip>
15427 #include <type_traits>
15428 
15429 namespace Catch {
15430 
15431 namespace {
15432 
15433  size_t trailingBytes(unsigned char c) {
15434  if ((c & 0xE0) == 0xC0) {
15435  return 2;
15436  }
15437  if ((c & 0xF0) == 0xE0) {
15438  return 3;
15439  }
15440  if ((c & 0xF8) == 0xF0) {
15441  return 4;
15442  }
15443  CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15444  }
15445 
15446  uint32_t headerValue(unsigned char c) {
15447  if ((c & 0xE0) == 0xC0) {
15448  return c & 0x1F;
15449  }
15450  if ((c & 0xF0) == 0xE0) {
15451  return c & 0x0F;
15452  }
15453  if ((c & 0xF8) == 0xF0) {
15454  return c & 0x07;
15455  }
15456  CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15457  }
15458 
15459  void hexEscapeChar(std::ostream& os, unsigned char c) {
15460  std::ios_base::fmtflags f(os.flags());
15461  os << "\\x"
15462  << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15463  << static_cast<int>(c);
15464  os.flags(f);
15465  }
15466 
15467  bool shouldNewline(XmlFormatting fmt) {
15468  return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15469  }
15470 
15471  bool shouldIndent(XmlFormatting fmt) {
15472  return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15473  }
15474 
15475 } // anonymous namespace
15476 
15477  XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15478  return static_cast<XmlFormatting>(
15479  static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15480  static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15481  );
15482  }
15483 
15484  XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15485  return static_cast<XmlFormatting>(
15486  static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15487  static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15488  );
15489  }
15490 
15491  XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
15492  : m_str( str ),
15493  m_forWhat( forWhat )
15494  {}
15495 
15496  void XmlEncode::encodeTo( std::ostream& os ) const {
15497  // Apostrophe escaping not necessary if we always use " to write attributes
15498  // (see: http://www.w3.org/TR/xml/#syntax)
15499 
15500  for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15501  unsigned char c = m_str[idx];
15502  switch (c) {
15503  case '<': os << "&lt;"; break;
15504  case '&': os << "&amp;"; break;
15505 
15506  case '>':
15507  // See: http://www.w3.org/TR/xml/#syntax
15508  if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15509  os << "&gt;";
15510  else
15511  os << c;
15512  break;
15513 
15514  case '\"':
15515  if (m_forWhat == ForAttributes)
15516  os << "&quot;";
15517  else
15518  os << c;
15519  break;
15520 
15521  default:
15522  // Check for control characters and invalid utf-8
15523 
15524  // Escape control characters in standard ascii
15525  // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15526  if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15527  hexEscapeChar(os, c);
15528  break;
15529  }
15530 
15531  // Plain ASCII: Write it to stream
15532  if (c < 0x7F) {
15533  os << c;
15534  break;
15535  }
15536 
15537  // UTF-8 territory
15538  // Check if the encoding is valid and if it is not, hex escape bytes.
15539  // Important: We do not check the exact decoded values for validity, only the encoding format
15540  // First check that this bytes is a valid lead byte:
15541  // This means that it is not encoded as 1111 1XXX
15542  // Or as 10XX XXXX
15543  if (c < 0xC0 ||
15544  c >= 0xF8) {
15545  hexEscapeChar(os, c);
15546  break;
15547  }
15548 
15549  auto encBytes = trailingBytes(c);
15550  // Are there enough bytes left to avoid accessing out-of-bounds memory?
15551  if (idx + encBytes - 1 >= m_str.size()) {
15552  hexEscapeChar(os, c);
15553  break;
15554  }
15555  // The header is valid, check data
15556  // The next encBytes bytes must together be a valid utf-8
15557  // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15558  bool valid = true;
15559  uint32_t value = headerValue(c);
15560  for (std::size_t n = 1; n < encBytes; ++n) {
15561  unsigned char nc = m_str[idx + n];
15562  valid &= ((nc & 0xC0) == 0x80);
15563  value = (value << 6) | (nc & 0x3F);
15564  }
15565 
15566  if (
15567  // Wrong bit pattern of following bytes
15568  (!valid) ||
15569  // Overlong encodings
15570  (value < 0x80) ||
15571  (0x80 <= value && value < 0x800 && encBytes > 2) ||
15572  (0x800 < value && value < 0x10000 && encBytes > 3) ||
15573  // Encoded value out of range
15574  (value >= 0x110000)
15575  ) {
15576  hexEscapeChar(os, c);
15577  break;
15578  }
15579 
15580  // If we got here, this is in fact a valid(ish) utf-8 sequence
15581  for (std::size_t n = 0; n < encBytes; ++n) {
15582  os << m_str[idx + n];
15583  }
15584  idx += encBytes - 1;
15585  break;
15586  }
15587  }
15588  }
15589 
15590  std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
15591  xmlEncode.encodeTo( os );
15592  return os;
15593  }
15594 
15595  XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15596  : m_writer( writer ),
15597  m_fmt(fmt)
15598  {}
15599 
15600  XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15601  : m_writer( other.m_writer ),
15602  m_fmt(other.m_fmt)
15603  {
15604  other.m_writer = nullptr;
15605  other.m_fmt = XmlFormatting::None;
15606  }
15607  XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15608  if ( m_writer ) {
15609  m_writer->endElement();
15610  }
15611  m_writer = other.m_writer;
15612  other.m_writer = nullptr;
15613  m_fmt = other.m_fmt;
15614  other.m_fmt = XmlFormatting::None;
15615  return *this;
15616  }
15617 
15618  XmlWriter::ScopedElement::~ScopedElement() {
15619  if (m_writer) {
15620  m_writer->endElement(m_fmt);
15621  }
15622  }
15623 
15624  XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
15625  m_writer->writeText( text, fmt );
15626  return *this;
15627  }
15628 
15629  XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15630  {
15631  writeDeclaration();
15632  }
15633 
15634  XmlWriter::~XmlWriter() {
15635  while (!m_tags.empty()) {
15636  endElement();
15637  }
15638  newlineIfNecessary();
15639  }
15640 
15641  XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
15642  ensureTagClosed();
15643  newlineIfNecessary();
15644  if (shouldIndent(fmt)) {
15645  m_os << m_indent;
15646  m_indent += " ";
15647  }
15648  m_os << '<' << name;
15649  m_tags.push_back( name );
15650  m_tagIsOpen = true;
15651  applyFormatting(fmt);
15652  return *this;
15653  }
15654 
15655  XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
15656  ScopedElement scoped( this, fmt );
15657  startElement( name, fmt );
15658  return scoped;
15659  }
15660 
15661  XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15662  m_indent = m_indent.substr(0, m_indent.size() - 2);
15663 
15664  if( m_tagIsOpen ) {
15665  m_os << "/>";
15666  m_tagIsOpen = false;
15667  } else {
15668  newlineIfNecessary();
15669  if (shouldIndent(fmt)) {
15670  m_os << m_indent;
15671  }
15672  m_os << "</" << m_tags.back() << ">";
15673  }
15674  m_os << std::flush;
15675  applyFormatting(fmt);
15676  m_tags.pop_back();
15677  return *this;
15678  }
15679 
15680  XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
15681  if( !name.empty() && !attribute.empty() )
15682  m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
15683  return *this;
15684  }
15685 
15686  XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
15687  m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
15688  return *this;
15689  }
15690 
15691  XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
15692  if( !text.empty() ){
15693  bool tagWasOpen = m_tagIsOpen;
15694  ensureTagClosed();
15695  if (tagWasOpen && shouldIndent(fmt)) {
15696  m_os << m_indent;
15697  }
15698  m_os << XmlEncode( text );
15699  applyFormatting(fmt);
15700  }
15701  return *this;
15702  }
15703 
15704  XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
15705  ensureTagClosed();
15706  if (shouldIndent(fmt)) {
15707  m_os << m_indent;
15708  }
15709  m_os << "<!--" << text << "-->";
15710  applyFormatting(fmt);
15711  return *this;
15712  }
15713 
15714  void XmlWriter::writeStylesheetRef( std::string const& url ) {
15715  m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15716  }
15717 
15718  XmlWriter& XmlWriter::writeBlankLine() {
15719  ensureTagClosed();
15720  m_os << '\n';
15721  return *this;
15722  }
15723 
15724  void XmlWriter::ensureTagClosed() {
15725  if( m_tagIsOpen ) {
15726  m_os << '>' << std::flush;
15727  newlineIfNecessary();
15728  m_tagIsOpen = false;
15729  }
15730  }
15731 
15732  void XmlWriter::applyFormatting(XmlFormatting fmt) {
15733  m_needsNewline = shouldNewline(fmt);
15734  }
15735 
15736  void XmlWriter::writeDeclaration() {
15737  m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15738  }
15739 
15740  void XmlWriter::newlineIfNecessary() {
15741  if( m_needsNewline ) {
15742  m_os << std::endl;
15743  m_needsNewline = false;
15744  }
15745  }
15746 }
15747 // end catch_xmlwriter.cpp
15748 // start catch_reporter_bases.cpp
15749 
15750 #include <cstring>
15751 #include <cfloat>
15752 #include <cstdio>
15753 #include <cassert>
15754 #include <memory>
15755 
15756 namespace Catch {
15757  void prepareExpandedExpression(AssertionResult& result) {
15758  result.getExpandedExpression();
15759  }
15760 
15761  // Because formatting using c++ streams is stateful, drop down to C is required
15762  // Alternatively we could use stringstream, but its performance is... not good.
15763  std::string getFormattedDuration( double duration ) {
15764  // Max exponent + 1 is required to represent the whole part
15765  // + 1 for decimal point
15766  // + 3 for the 3 decimal places
15767  // + 1 for null terminator
15768  const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15769  char buffer[maxDoubleSize];
15770 
15771  // Save previous errno, to prevent sprintf from overwriting it
15772  ErrnoGuard guard;
15773 #ifdef _MSC_VER
15774  sprintf_s(buffer, "%.3f", duration);
15775 #else
15776  std::sprintf(buffer, "%.3f", duration);
15777 #endif
15778  return std::string(buffer);
15779  }
15780 
15781  bool shouldShowDuration( IConfig const& config, double duration ) {
15782  if ( config.showDurations() == ShowDurations::Always ) {
15783  return true;
15784  }
15785  if ( config.showDurations() == ShowDurations::Never ) {
15786  return false;
15787  }
15788  const double min = config.minDuration();
15789  return min >= 0 && duration >= min;
15790  }
15791 
15792  std::string serializeFilters( std::vector<std::string> const& container ) {
15793  ReusableStringStream oss;
15794  bool first = true;
15795  for (auto&& filter : container)
15796  {
15797  if (!first)
15798  oss << ' ';
15799  else
15800  first = false;
15801 
15802  oss << filter;
15803  }
15804  return oss.str();
15805  }
15806 
15807  TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15808  :StreamingReporterBase(_config) {}
15809 
15810  std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15811  return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15812  }
15813 
15814  void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15815 
15816  bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15817  return false;
15818  }
15819 
15820 } // end namespace Catch
15821 // end catch_reporter_bases.cpp
15822 // start catch_reporter_compact.cpp
15823 
15824 namespace {
15825 
15826 #ifdef CATCH_PLATFORM_MAC
15827  const char* failedString() { return "FAILED"; }
15828  const char* passedString() { return "PASSED"; }
15829 #else
15830  const char* failedString() { return "failed"; }
15831  const char* passedString() { return "passed"; }
15832 #endif
15833 
15834  // Colour::LightGrey
15835  Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15836 
15837  std::string bothOrAll( std::size_t count ) {
15838  return count == 1 ? std::string() :
15839  count == 2 ? "both " : "all " ;
15840  }
15841 
15842 } // anon namespace
15843 
15844 namespace Catch {
15845 namespace {
15846 // Colour, message variants:
15847 // - white: No tests ran.
15848 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15849 // - white: Passed [both/all] N test cases (no assertions).
15850 // - red: Failed N tests cases, failed M assertions.
15851 // - green: Passed [both/all] N tests cases with M assertions.
15852 void printTotals(std::ostream& out, const Totals& totals) {
15853  if (totals.testCases.total() == 0) {
15854  out << "No tests ran.";
15855  } else if (totals.testCases.failed == totals.testCases.total()) {
15856  Colour colour(Colour::ResultError);
15857  const std::string qualify_assertions_failed =
15858  totals.assertions.failed == totals.assertions.total() ?
15859  bothOrAll(totals.assertions.failed) : std::string();
15860  out <<
15861  "Failed " << bothOrAll(totals.testCases.failed)
15862  << pluralise(totals.testCases.failed, "test case") << ", "
15863  "failed " << qualify_assertions_failed <<
15864  pluralise(totals.assertions.failed, "assertion") << '.';
15865  } else if (totals.assertions.total() == 0) {
15866  out <<
15867  "Passed " << bothOrAll(totals.testCases.total())
15868  << pluralise(totals.testCases.total(), "test case")
15869  << " (no assertions).";
15870  } else if (totals.assertions.failed) {
15871  Colour colour(Colour::ResultError);
15872  out <<
15873  "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15874  "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15875  } else {
15876  Colour colour(Colour::ResultSuccess);
15877  out <<
15878  "Passed " << bothOrAll(totals.testCases.passed)
15879  << pluralise(totals.testCases.passed, "test case") <<
15880  " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15881  }
15882 }
15883 
15884 // Implementation of CompactReporter formatting
15885 class AssertionPrinter {
15886 public:
15887  AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15888  AssertionPrinter(AssertionPrinter const&) = delete;
15889  AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15890  : stream(_stream)
15891  , result(_stats.assertionResult)
15892  , messages(_stats.infoMessages)
15893  , itMessage(_stats.infoMessages.begin())
15894  , printInfoMessages(_printInfoMessages) {}
15895 
15896  void print() {
15897  printSourceInfo();
15898 
15899  itMessage = messages.begin();
15900 
15901  switch (result.getResultType()) {
15902  case ResultWas::Ok:
15903  printResultType(Colour::ResultSuccess, passedString());
15904  printOriginalExpression();
15905  printReconstructedExpression();
15906  if (!result.hasExpression())
15907  printRemainingMessages(Colour::None);
15908  else
15909  printRemainingMessages();
15910  break;
15911  case ResultWas::ExpressionFailed:
15912  if (result.isOk())
15913  printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15914  else
15915  printResultType(Colour::Error, failedString());
15916  printOriginalExpression();
15917  printReconstructedExpression();
15918  printRemainingMessages();
15919  break;
15920  case ResultWas::ThrewException:
15921  printResultType(Colour::Error, failedString());
15922  printIssue("unexpected exception with message:");
15923  printMessage();
15924  printExpressionWas();
15925  printRemainingMessages();
15926  break;
15927  case ResultWas::FatalErrorCondition:
15928  printResultType(Colour::Error, failedString());
15929  printIssue("fatal error condition with message:");
15930  printMessage();
15931  printExpressionWas();
15932  printRemainingMessages();
15933  break;
15934  case ResultWas::DidntThrowException:
15935  printResultType(Colour::Error, failedString());
15936  printIssue("expected exception, got none");
15937  printExpressionWas();
15938  printRemainingMessages();
15939  break;
15940  case ResultWas::Info:
15941  printResultType(Colour::None, "info");
15942  printMessage();
15943  printRemainingMessages();
15944  break;
15945  case ResultWas::Warning:
15946  printResultType(Colour::None, "warning");
15947  printMessage();
15948  printRemainingMessages();
15949  break;
15950  case ResultWas::ExplicitFailure:
15951  printResultType(Colour::Error, failedString());
15952  printIssue("explicitly");
15953  printRemainingMessages(Colour::None);
15954  break;
15955  // These cases are here to prevent compiler warnings
15956  case ResultWas::Unknown:
15957  case ResultWas::FailureBit:
15958  case ResultWas::Exception:
15959  printResultType(Colour::Error, "** internal error **");
15960  break;
15961  }
15962  }
15963 
15964 private:
15965  void printSourceInfo() const {
15966  Colour colourGuard(Colour::FileName);
15967  stream << result.getSourceInfo() << ':';
15968  }
15969 
15970  void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15971  if (!passOrFail.empty()) {
15972  {
15973  Colour colourGuard(colour);
15974  stream << ' ' << passOrFail;
15975  }
15976  stream << ':';
15977  }
15978  }
15979 
15980  void printIssue(std::string const& issue) const {
15981  stream << ' ' << issue;
15982  }
15983 
15984  void printExpressionWas() {
15985  if (result.hasExpression()) {
15986  stream << ';';
15987  {
15988  Colour colour(dimColour());
15989  stream << " expression was:";
15990  }
15991  printOriginalExpression();
15992  }
15993  }
15994 
15995  void printOriginalExpression() const {
15996  if (result.hasExpression()) {
15997  stream << ' ' << result.getExpression();
15998  }
15999  }
16000 
16001  void printReconstructedExpression() const {
16002  if (result.hasExpandedExpression()) {
16003  {
16004  Colour colour(dimColour());
16005  stream << " for: ";
16006  }
16007  stream << result.getExpandedExpression();
16008  }
16009  }
16010 
16011  void printMessage() {
16012  if (itMessage != messages.end()) {
16013  stream << " '" << itMessage->message << '\'';
16014  ++itMessage;
16015  }
16016  }
16017 
16018  void printRemainingMessages(Colour::Code colour = dimColour()) {
16019  if (itMessage == messages.end())
16020  return;
16021 
16022  const auto itEnd = messages.cend();
16023  const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16024 
16025  {
16026  Colour colourGuard(colour);
16027  stream << " with " << pluralise(N, "message") << ':';
16028  }
16029 
16030  while (itMessage != itEnd) {
16031  // If this assertion is a warning ignore any INFO messages
16032  if (printInfoMessages || itMessage->type != ResultWas::Info) {
16033  printMessage();
16034  if (itMessage != itEnd) {
16035  Colour colourGuard(dimColour());
16036  stream << " and";
16037  }
16038  continue;
16039  }
16040  ++itMessage;
16041  }
16042  }
16043 
16044 private:
16045  std::ostream& stream;
16046  AssertionResult const& result;
16047  std::vector<MessageInfo> messages;
16048  std::vector<MessageInfo>::const_iterator itMessage;
16049  bool printInfoMessages;
16050 };
16051 
16052 } // anon namespace
16053 
16054  std::string CompactReporter::getDescription() {
16055  return "Reports test results on a single line, suitable for IDEs";
16056  }
16057 
16058  void CompactReporter::noMatchingTestCases( std::string const& spec ) {
16059  stream << "No test cases matched '" << spec << '\'' << std::endl;
16060  }
16061 
16062  void CompactReporter::assertionStarting( AssertionInfo const& ) {}
16063 
16064  bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
16065  AssertionResult const& result = _assertionStats.assertionResult;
16066 
16067  bool printInfoMessages = true;
16068 
16069  // Drop out if result was successful and we're not printing those
16070  if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16071  if( result.getResultType() != ResultWas::Warning )
16072  return false;
16073  printInfoMessages = false;
16074  }
16075 
16076  AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16077  printer.print();
16078 
16079  stream << std::endl;
16080  return true;
16081  }
16082 
16083  void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16084  double dur = _sectionStats.durationInSeconds;
16085  if ( shouldShowDuration( *m_config, dur ) ) {
16086  stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16087  }
16088  }
16089 
16090  void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
16091  printTotals( stream, _testRunStats.totals );
16092  stream << '\n' << std::endl;
16093  StreamingReporterBase::testRunEnded( _testRunStats );
16094  }
16095 
16096  CompactReporter::~CompactReporter() {}
16097 
16098  CATCH_REGISTER_REPORTER( "compact", CompactReporter )
16099 
16100 } // end namespace Catch
16101 // end catch_reporter_compact.cpp
16102 // start catch_reporter_console.cpp
16103 
16104 #include <cfloat>
16105 #include <cstdio>
16106 
16107 #if defined(_MSC_VER)
16108 #pragma warning(push)
16109 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16110  // Note that 4062 (not all labels are handled and default is missing) is enabled
16111 #endif
16112 
16113 #if defined(__clang__)
16114 # pragma clang diagnostic push
16115 // For simplicity, benchmarking-only helpers are always enabled
16116 # pragma clang diagnostic ignored "-Wunused-function"
16117 #endif
16118 
16119 namespace Catch {
16120 
16121 namespace {
16122 
16123 // Formatter impl for ConsoleReporter
16124 class ConsoleAssertionPrinter {
16125 public:
16126  ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
16127  ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16128  ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
16129  : stream(_stream),
16130  stats(_stats),
16131  result(_stats.assertionResult),
16132  colour(Colour::None),
16133  message(result.getMessage()),
16134  messages(_stats.infoMessages),
16135  printInfoMessages(_printInfoMessages) {
16136  switch (result.getResultType()) {
16137  case ResultWas::Ok:
16138  colour = Colour::Success;
16139  passOrFail = "PASSED";
16140  //if( result.hasMessage() )
16141  if (_stats.infoMessages.size() == 1)
16142  messageLabel = "with message";
16143  if (_stats.infoMessages.size() > 1)
16144  messageLabel = "with messages";
16145  break;
16146  case ResultWas::ExpressionFailed:
16147  if (result.isOk()) {
16148  colour = Colour::Success;
16149  passOrFail = "FAILED - but was ok";
16150  } else {
16151  colour = Colour::Error;
16152  passOrFail = "FAILED";
16153  }
16154  if (_stats.infoMessages.size() == 1)
16155  messageLabel = "with message";
16156  if (_stats.infoMessages.size() > 1)
16157  messageLabel = "with messages";
16158  break;
16159  case ResultWas::ThrewException:
16160  colour = Colour::Error;
16161  passOrFail = "FAILED";
16162  messageLabel = "due to unexpected exception with ";
16163  if (_stats.infoMessages.size() == 1)
16164  messageLabel += "message";
16165  if (_stats.infoMessages.size() > 1)
16166  messageLabel += "messages";
16167  break;
16168  case ResultWas::FatalErrorCondition:
16169  colour = Colour::Error;
16170  passOrFail = "FAILED";
16171  messageLabel = "due to a fatal error condition";
16172  break;
16173  case ResultWas::DidntThrowException:
16174  colour = Colour::Error;
16175  passOrFail = "FAILED";
16176  messageLabel = "because no exception was thrown where one was expected";
16177  break;
16178  case ResultWas::Info:
16179  messageLabel = "info";
16180  break;
16181  case ResultWas::Warning:
16182  messageLabel = "warning";
16183  break;
16184  case ResultWas::ExplicitFailure:
16185  passOrFail = "FAILED";
16186  colour = Colour::Error;
16187  if (_stats.infoMessages.size() == 1)
16188  messageLabel = "explicitly with message";
16189  if (_stats.infoMessages.size() > 1)
16190  messageLabel = "explicitly with messages";
16191  break;
16192  // These cases are here to prevent compiler warnings
16193  case ResultWas::Unknown:
16194  case ResultWas::FailureBit:
16195  case ResultWas::Exception:
16196  passOrFail = "** internal error **";
16197  colour = Colour::Error;
16198  break;
16199  }
16200  }
16201 
16202  void print() const {
16203  printSourceInfo();
16204  if (stats.totals.assertions.total() > 0) {
16205  printResultType();
16206  printOriginalExpression();
16207  printReconstructedExpression();
16208  } else {
16209  stream << '\n';
16210  }
16211  printMessage();
16212  }
16213 
16214 private:
16215  void printResultType() const {
16216  if (!passOrFail.empty()) {
16217  Colour colourGuard(colour);
16218  stream << passOrFail << ":\n";
16219  }
16220  }
16221  void printOriginalExpression() const {
16222  if (result.hasExpression()) {
16223  Colour colourGuard(Colour::OriginalExpression);
16224  stream << " ";
16225  stream << result.getExpressionInMacro();
16226  stream << '\n';
16227  }
16228  }
16229  void printReconstructedExpression() const {
16230  if (result.hasExpandedExpression()) {
16231  stream << "with expansion:\n";
16232  Colour colourGuard(Colour::ReconstructedExpression);
16233  stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16234  }
16235  }
16236  void printMessage() const {
16237  if (!messageLabel.empty())
16238  stream << messageLabel << ':' << '\n';
16239  for (auto const& msg : messages) {
16240  // If this assertion is a warning ignore any INFO messages
16241  if (printInfoMessages || msg.type != ResultWas::Info)
16242  stream << Column(msg.message).indent(2) << '\n';
16243  }
16244  }
16245  void printSourceInfo() const {
16246  Colour colourGuard(Colour::FileName);
16247  stream << result.getSourceInfo() << ": ";
16248  }
16249 
16250  std::ostream& stream;
16251  AssertionStats const& stats;
16252  AssertionResult const& result;
16253  Colour::Code colour;
16254  std::string passOrFail;
16255  std::string messageLabel;
16256  std::string message;
16257  std::vector<MessageInfo> messages;
16258  bool printInfoMessages;
16259 };
16260 
16261 std::size_t makeRatio(std::size_t number, std::size_t total) {
16262  std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16263  return (ratio == 0 && number > 0) ? 1 : ratio;
16264 }
16265 
16266 std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16267  if (i > j && i > k)
16268  return i;
16269  else if (j > k)
16270  return j;
16271  else
16272  return k;
16273 }
16274 
16275 struct ColumnInfo {
16276  enum Justification { Left, Right };
16277  std::string name;
16278  int width;
16279  Justification justification;
16280 };
16281 struct ColumnBreak {};
16282 struct RowBreak {};
16283 
16284 class Duration {
16285  enum class Unit {
16286  Auto,
16287  Nanoseconds,
16288  Microseconds,
16289  Milliseconds,
16290  Seconds,
16291  Minutes
16292  };
16293  static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16294  static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16295  static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16296  static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16297 
16298  double m_inNanoseconds;
16299  Unit m_units;
16300 
16301 public:
16302  explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16303  : m_inNanoseconds(inNanoseconds),
16304  m_units(units) {
16305  if (m_units == Unit::Auto) {
16306  if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16307  m_units = Unit::Nanoseconds;
16308  else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16309  m_units = Unit::Microseconds;
16310  else if (m_inNanoseconds < s_nanosecondsInASecond)
16311  m_units = Unit::Milliseconds;
16312  else if (m_inNanoseconds < s_nanosecondsInAMinute)
16313  m_units = Unit::Seconds;
16314  else
16315  m_units = Unit::Minutes;
16316  }
16317 
16318  }
16319 
16320  auto value() const -> double {
16321  switch (m_units) {
16322  case Unit::Microseconds:
16323  return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16324  case Unit::Milliseconds:
16325  return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16326  case Unit::Seconds:
16327  return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16328  case Unit::Minutes:
16329  return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16330  default:
16331  return m_inNanoseconds;
16332  }
16333  }
16334  auto unitsAsString() const -> std::string {
16335  switch (m_units) {
16336  case Unit::Nanoseconds:
16337  return "ns";
16338  case Unit::Microseconds:
16339  return "us";
16340  case Unit::Milliseconds:
16341  return "ms";
16342  case Unit::Seconds:
16343  return "s";
16344  case Unit::Minutes:
16345  return "m";
16346  default:
16347  return "** internal error **";
16348  }
16349 
16350  }
16351  friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
16352  return os << duration.value() << ' ' << duration.unitsAsString();
16353  }
16354 };
16355 } // end anon namespace
16356 
16357 class TablePrinter {
16358  std::ostream& m_os;
16359  std::vector<ColumnInfo> m_columnInfos;
16360  std::ostringstream m_oss;
16361  int m_currentColumn = -1;
16362  bool m_isOpen = false;
16363 
16364 public:
16365  TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16366  : m_os( os ),
16367  m_columnInfos( std::move( columnInfos ) ) {}
16368 
16369  auto columnInfos() const -> std::vector<ColumnInfo> const& {
16370  return m_columnInfos;
16371  }
16372 
16373  void open() {
16374  if (!m_isOpen) {
16375  m_isOpen = true;
16376  *this << RowBreak();
16377 
16378  Columns headerCols;
16379  Spacer spacer(2);
16380  for (auto const& info : m_columnInfos) {
16381  headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16382  headerCols += spacer;
16383  }
16384  m_os << headerCols << '\n';
16385 
16386  m_os << Catch::getLineOfChars<'-'>() << '\n';
16387  }
16388  }
16389  void close() {
16390  if (m_isOpen) {
16391  *this << RowBreak();
16392  m_os << std::endl;
16393  m_isOpen = false;
16394  }
16395  }
16396 
16397  template<typename T>
16398  friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
16399  tp.m_oss << value;
16400  return tp;
16401  }
16402 
16403  friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16404  auto colStr = tp.m_oss.str();
16405  const auto strSize = colStr.size();
16406  tp.m_oss.str("");
16407  tp.open();
16408  if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16409  tp.m_currentColumn = -1;
16410  tp.m_os << '\n';
16411  }
16412  tp.m_currentColumn++;
16413 
16414  auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16415  auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16416  ? std::string(colInfo.width - (strSize + 1), ' ')
16417  : std::string();
16418  if (colInfo.justification == ColumnInfo::Left)
16419  tp.m_os << colStr << padding << ' ';
16420  else
16421  tp.m_os << padding << colStr << ' ';
16422  return tp;
16423  }
16424 
16425  friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16426  if (tp.m_currentColumn > 0) {
16427  tp.m_os << '\n';
16428  tp.m_currentColumn = -1;
16429  }
16430  return tp;
16431  }
16432 };
16433 
16434 ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16435  : StreamingReporterBase(config),
16436  m_tablePrinter(new TablePrinter(config.stream(),
16437  [&config]() -> std::vector<ColumnInfo> {
16438  if (config.fullConfig()->benchmarkNoAnalysis())
16439  {
16440  return{
16441  { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16442  { " samples", 14, ColumnInfo::Right },
16443  { " iterations", 14, ColumnInfo::Right },
16444  { " mean", 14, ColumnInfo::Right }
16445  };
16446  }
16447  else
16448  {
16449  return{
16450  { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16451  { "samples mean std dev", 14, ColumnInfo::Right },
16452  { "iterations low mean low std dev", 14, ColumnInfo::Right },
16453  { "estimated high mean high std dev", 14, ColumnInfo::Right }
16454  };
16455  }
16456  }())) {}
16457 ConsoleReporter::~ConsoleReporter() = default;
16458 
16459 std::string ConsoleReporter::getDescription() {
16460  return "Reports test results as plain lines of text";
16461 }
16462 
16463 void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16464  stream << "No test cases matched '" << spec << '\'' << std::endl;
16465 }
16466 
16467 void ConsoleReporter::reportInvalidArguments(std::string const&arg){
16468  stream << "Invalid Filter: " << arg << std::endl;
16469 }
16470 
16471 void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16472 
16473 bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16474  AssertionResult const& result = _assertionStats.assertionResult;
16475 
16476  bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16477 
16478  // Drop out if result was successful but we're not printing them.
16479  if (!includeResults && result.getResultType() != ResultWas::Warning)
16480  return false;
16481 
16482  lazyPrint();
16483 
16484  ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16485  printer.print();
16486  stream << std::endl;
16487  return true;
16488 }
16489 
16490 void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16491  m_tablePrinter->close();
16492  m_headerPrinted = false;
16493  StreamingReporterBase::sectionStarting(_sectionInfo);
16494 }
16495 void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16496  m_tablePrinter->close();
16497  if (_sectionStats.missingAssertions) {
16498  lazyPrint();
16499  Colour colour(Colour::ResultError);
16500  if (m_sectionStack.size() > 1)
16501  stream << "\nNo assertions in section";
16502  else
16503  stream << "\nNo assertions in test case";
16504  stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16505  }
16506  double dur = _sectionStats.durationInSeconds;
16507  if (shouldShowDuration(*m_config, dur)) {
16508  stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16509  }
16510  if (m_headerPrinted) {
16511  m_headerPrinted = false;
16512  }
16513  StreamingReporterBase::sectionEnded(_sectionStats);
16514 }
16515 
16516 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16517 void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16518  lazyPrintWithoutClosingBenchmarkTable();
16519 
16520  auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16521 
16522  bool firstLine = true;
16523  for (auto line : nameCol) {
16524  if (!firstLine)
16525  (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16526  else
16527  firstLine = false;
16528 
16529  (*m_tablePrinter) << line << ColumnBreak();
16530  }
16531 }
16532 
16533 void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16534  (*m_tablePrinter) << info.samples << ColumnBreak()
16535  << info.iterations << ColumnBreak();
16536  if (!m_config->benchmarkNoAnalysis())
16537  (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16538 }
16539 void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16540  if (m_config->benchmarkNoAnalysis())
16541  {
16542  (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16543  }
16544  else
16545  {
16546  (*m_tablePrinter) << ColumnBreak()
16547  << Duration(stats.mean.point.count()) << ColumnBreak()
16548  << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16549  << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16550  << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16551  << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16552  << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16553  }
16554 }
16555 
16556 void ConsoleReporter::benchmarkFailed(std::string const& error) {
16557  Colour colour(Colour::Red);
16558  (*m_tablePrinter)
16559  << "Benchmark failed (" << error << ')'
16560  << ColumnBreak() << RowBreak();
16561 }
16562 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16563 
16564 void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16565  m_tablePrinter->close();
16566  StreamingReporterBase::testCaseEnded(_testCaseStats);
16567  m_headerPrinted = false;
16568 }
16569 void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16570  if (currentGroupInfo.used) {
16571  printSummaryDivider();
16572  stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16573  printTotals(_testGroupStats.totals);
16574  stream << '\n' << std::endl;
16575  }
16576  StreamingReporterBase::testGroupEnded(_testGroupStats);
16577 }
16578 void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16579  printTotalsDivider(_testRunStats.totals);
16580  printTotals(_testRunStats.totals);
16581  stream << std::endl;
16582  StreamingReporterBase::testRunEnded(_testRunStats);
16583 }
16584 void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16585  StreamingReporterBase::testRunStarting(_testInfo);
16586  printTestFilters();
16587 }
16588 
16589 void ConsoleReporter::lazyPrint() {
16590 
16591  m_tablePrinter->close();
16592  lazyPrintWithoutClosingBenchmarkTable();
16593 }
16594 
16595 void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16596 
16597  if (!currentTestRunInfo.used)
16598  lazyPrintRunInfo();
16599  if (!currentGroupInfo.used)
16600  lazyPrintGroupInfo();
16601 
16602  if (!m_headerPrinted) {
16603  printTestCaseAndSectionHeader();
16604  m_headerPrinted = true;
16605  }
16606 }
16607 void ConsoleReporter::lazyPrintRunInfo() {
16608  stream << '\n' << getLineOfChars<'~'>() << '\n';
16609  Colour colour(Colour::SecondaryText);
16610  stream << currentTestRunInfo->name
16611  << " is a Catch v" << libraryVersion() << " host application.\n"
16612  << "Run with -? for options\n\n";
16613 
16614  if (m_config->rngSeed() != 0)
16615  stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16616 
16617  currentTestRunInfo.used = true;
16618 }
16619 void ConsoleReporter::lazyPrintGroupInfo() {
16620  if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16621  printClosedHeader("Group: " + currentGroupInfo->name);
16622  currentGroupInfo.used = true;
16623  }
16624 }
16625 void ConsoleReporter::printTestCaseAndSectionHeader() {
16626  assert(!m_sectionStack.empty());
16627  printOpenHeader(currentTestCaseInfo->name);
16628 
16629  if (m_sectionStack.size() > 1) {
16630  Colour colourGuard(Colour::Headers);
16631 
16632  auto
16633  it = m_sectionStack.begin() + 1, // Skip first section (test case)
16634  itEnd = m_sectionStack.end();
16635  for (; it != itEnd; ++it)
16636  printHeaderString(it->name, 2);
16637  }
16638 
16639  SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16640 
16641  stream << getLineOfChars<'-'>() << '\n';
16642  Colour colourGuard(Colour::FileName);
16643  stream << lineInfo << '\n';
16644  stream << getLineOfChars<'.'>() << '\n' << std::endl;
16645 }
16646 
16647 void ConsoleReporter::printClosedHeader(std::string const& _name) {
16648  printOpenHeader(_name);
16649  stream << getLineOfChars<'.'>() << '\n';
16650 }
16651 void ConsoleReporter::printOpenHeader(std::string const& _name) {
16652  stream << getLineOfChars<'-'>() << '\n';
16653  {
16654  Colour colourGuard(Colour::Headers);
16655  printHeaderString(_name);
16656  }
16657 }
16658 
16659 // if string has a : in first line will set indent to follow it on
16660 // subsequent lines
16661 void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16662  std::size_t i = _string.find(": ");
16663  if (i != std::string::npos)
16664  i += 2;
16665  else
16666  i = 0;
16667  stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16668 }
16669 
16670 struct SummaryColumn {
16671 
16672  SummaryColumn( std::string _label, Colour::Code _colour )
16673  : label( std::move( _label ) ),
16674  colour( _colour ) {}
16675  SummaryColumn addRow( std::size_t count ) {
16677  rss << count;
16678  std::string row = rss.str();
16679  for (auto& oldRow : rows) {
16680  while (oldRow.size() < row.size())
16681  oldRow = ' ' + oldRow;
16682  while (oldRow.size() > row.size())
16683  row = ' ' + row;
16684  }
16685  rows.push_back(row);
16686  return *this;
16687  }
16688 
16689  std::string label;
16690  Colour::Code colour;
16691  std::vector<std::string> rows;
16692 
16693 };
16694 
16695 void ConsoleReporter::printTotals( Totals const& totals ) {
16696  if (totals.testCases.total() == 0) {
16697  stream << Colour(Colour::Warning) << "No tests ran\n";
16698  } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16699  stream << Colour(Colour::ResultSuccess) << "All tests passed";
16700  stream << " ("
16701  << pluralise(totals.assertions.passed, "assertion") << " in "
16702  << pluralise(totals.testCases.passed, "test case") << ')'
16703  << '\n';
16704  } else {
16705 
16706  std::vector<SummaryColumn> columns;
16707  columns.push_back(SummaryColumn("", Colour::None)
16708  .addRow(totals.testCases.total())
16709  .addRow(totals.assertions.total()));
16710  columns.push_back(SummaryColumn("passed", Colour::Success)
16711  .addRow(totals.testCases.passed)
16712  .addRow(totals.assertions.passed));
16713  columns.push_back(SummaryColumn("failed", Colour::ResultError)
16714  .addRow(totals.testCases.failed)
16715  .addRow(totals.assertions.failed));
16716  columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16717  .addRow(totals.testCases.failedButOk)
16718  .addRow(totals.assertions.failedButOk));
16719 
16720  printSummaryRow("test cases", columns, 0);
16721  printSummaryRow("assertions", columns, 1);
16722  }
16723 }
16724 void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
16725  for (auto col : cols) {
16726  std::string value = col.rows[row];
16727  if (col.label.empty()) {
16728  stream << label << ": ";
16729  if (value != "0")
16730  stream << value;
16731  else
16732  stream << Colour(Colour::Warning) << "- none -";
16733  } else if (value != "0") {
16734  stream << Colour(Colour::LightGrey) << " | ";
16735  stream << Colour(col.colour)
16736  << value << ' ' << col.label;
16737  }
16738  }
16739  stream << '\n';
16740 }
16741 
16742 void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16743  if (totals.testCases.total() > 0) {
16744  std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16745  std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16746  std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16747  while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16748  findMax(failedRatio, failedButOkRatio, passedRatio)++;
16749  while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16750  findMax(failedRatio, failedButOkRatio, passedRatio)--;
16751 
16752  stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16753  stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16754  if (totals.testCases.allPassed())
16755  stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16756  else
16757  stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16758  } else {
16759  stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16760  }
16761  stream << '\n';
16762 }
16763 void ConsoleReporter::printSummaryDivider() {
16764  stream << getLineOfChars<'-'>() << '\n';
16765 }
16766 
16767 void ConsoleReporter::printTestFilters() {
16768  if (m_config->testSpec().hasFilters()) {
16769  Colour guard(Colour::BrightYellow);
16770  stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16771  }
16772 }
16773 
16774 CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16775 
16776 } // end namespace Catch
16777 
16778 #if defined(_MSC_VER)
16779 #pragma warning(pop)
16780 #endif
16781 
16782 #if defined(__clang__)
16783 # pragma clang diagnostic pop
16784 #endif
16785 // end catch_reporter_console.cpp
16786 // start catch_reporter_junit.cpp
16787 
16788 #include <cassert>
16789 #include <sstream>
16790 #include <ctime>
16791 #include <algorithm>
16792 
16793 namespace Catch {
16794 
16795  namespace {
16796  std::string getCurrentTimestamp() {
16797  // Beware, this is not reentrant because of backward compatibility issues
16798  // Also, UTC only, again because of backward compatibility (%z is C++11)
16799  time_t rawtime;
16800  std::time(&rawtime);
16801  auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16802 
16803 #ifdef _MSC_VER
16804  std::tm timeInfo = {};
16805  gmtime_s(&timeInfo, &rawtime);
16806 #else
16807  std::tm* timeInfo;
16808  timeInfo = std::gmtime(&rawtime);
16809 #endif
16810 
16811  char timeStamp[timeStampSize];
16812  const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
16813 
16814 #ifdef _MSC_VER
16815  std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16816 #else
16817  std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16818 #endif
16819  return std::string(timeStamp);
16820  }
16821 
16822  std::string fileNameTag(const std::vector<std::string> &tags) {
16823  auto it = std::find_if(begin(tags),
16824  end(tags),
16825  [] (std::string const& tag) {return tag.front() == '#'; });
16826  if (it != tags.end())
16827  return it->substr(1);
16828  return std::string();
16829  }
16830  } // anonymous namespace
16831 
16832  JunitReporter::JunitReporter( ReporterConfig const& _config )
16833  : CumulativeReporterBase( _config ),
16834  xml( _config.stream() )
16835  {
16836  m_reporterPrefs.shouldRedirectStdOut = true;
16837  m_reporterPrefs.shouldReportAllAssertions = true;
16838  }
16839 
16840  JunitReporter::~JunitReporter() {}
16841 
16842  std::string JunitReporter::getDescription() {
16843  return "Reports test results in an XML format that looks like Ant's junitreport target";
16844  }
16845 
16846  void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16847 
16848  void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
16849  CumulativeReporterBase::testRunStarting( runInfo );
16850  xml.startElement( "testsuites" );
16851  }
16852 
16853  void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16854  suiteTimer.start();
16855  stdOutForSuite.clear();
16856  stdErrForSuite.clear();
16857  unexpectedExceptions = 0;
16858  CumulativeReporterBase::testGroupStarting( groupInfo );
16859  }
16860 
16861  void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16862  m_okToFail = testCaseInfo.okToFail();
16863  }
16864 
16865  bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16866  if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16867  unexpectedExceptions++;
16868  return CumulativeReporterBase::assertionEnded( assertionStats );
16869  }
16870 
16871  void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16872  stdOutForSuite += testCaseStats.stdOut;
16873  stdErrForSuite += testCaseStats.stdErr;
16874  CumulativeReporterBase::testCaseEnded( testCaseStats );
16875  }
16876 
16877  void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16878  double suiteTime = suiteTimer.getElapsedSeconds();
16879  CumulativeReporterBase::testGroupEnded( testGroupStats );
16880  writeGroup( *m_testGroups.back(), suiteTime );
16881  }
16882 
16883  void JunitReporter::testRunEndedCumulative() {
16884  xml.endElement();
16885  }
16886 
16887  void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16888  XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16889 
16890  TestGroupStats const& stats = groupNode.value;
16891  xml.writeAttribute( "name", stats.groupInfo.name );
16892  xml.writeAttribute( "errors", unexpectedExceptions );
16893  xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16894  xml.writeAttribute( "tests", stats.totals.assertions.total() );
16895  xml.writeAttribute( "hostname", "tbd" ); // !TBD
16896  if( m_config->showDurations() == ShowDurations::Never )
16897  xml.writeAttribute( "time", "" );
16898  else
16899  xml.writeAttribute( "time", suiteTime );
16900  xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16901 
16902  // Write properties if there are any
16903  if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16904  auto properties = xml.scopedElement("properties");
16905  if (m_config->hasTestFilters()) {
16906  xml.scopedElement("property")
16907  .writeAttribute("name", "filters")
16908  .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16909  }
16910  if (m_config->rngSeed() != 0) {
16911  xml.scopedElement("property")
16912  .writeAttribute("name", "random-seed")
16913  .writeAttribute("value", m_config->rngSeed());
16914  }
16915  }
16916 
16917  // Write test cases
16918  for( auto const& child : groupNode.children )
16919  writeTestCase( *child );
16920 
16921  xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16922  xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16923  }
16924 
16925  void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16926  TestCaseStats const& stats = testCaseNode.value;
16927 
16928  // All test cases have exactly one section - which represents the
16929  // test case itself. That section may have 0-n nested sections
16930  assert( testCaseNode.children.size() == 1 );
16931  SectionNode const& rootSection = *testCaseNode.children.front();
16932 
16933  std::string className = stats.testInfo.className;
16934 
16935  if( className.empty() ) {
16936  className = fileNameTag(stats.testInfo.tags);
16937  if ( className.empty() )
16938  className = "global";
16939  }
16940 
16941  if ( !m_config->name().empty() )
16942  className = m_config->name() + "." + className;
16943 
16944  writeSection( className, "", rootSection );
16945  }
16946 
16947  void JunitReporter::writeSection( std::string const& className,
16948  std::string const& rootName,
16949  SectionNode const& sectionNode ) {
16950  std::string name = trim( sectionNode.stats.sectionInfo.name );
16951  if( !rootName.empty() )
16952  name = rootName + '/' + name;
16953 
16954  if( !sectionNode.assertions.empty() ||
16955  !sectionNode.stdOut.empty() ||
16956  !sectionNode.stdErr.empty() ) {
16957  XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16958  if( className.empty() ) {
16959  xml.writeAttribute( "classname", name );
16960  xml.writeAttribute( "name", "root" );
16961  }
16962  else {
16963  xml.writeAttribute( "classname", className );
16964  xml.writeAttribute( "name", name );
16965  }
16966  xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
16967  // This is not ideal, but it should be enough to mimic gtest's
16968  // junit output.
16969  // Ideally the JUnit reporter would also handle `skipTest`
16970  // events and write those out appropriately.
16971  xml.writeAttribute( "status", "run" );
16972 
16973  writeAssertions( sectionNode );
16974 
16975  if( !sectionNode.stdOut.empty() )
16976  xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
16977  if( !sectionNode.stdErr.empty() )
16978  xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
16979  }
16980  for( auto const& childNode : sectionNode.childSections )
16981  if( className.empty() )
16982  writeSection( name, "", *childNode );
16983  else
16984  writeSection( className, name, *childNode );
16985  }
16986 
16987  void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
16988  for( auto const& assertion : sectionNode.assertions )
16989  writeAssertion( assertion );
16990  }
16991 
16992  void JunitReporter::writeAssertion( AssertionStats const& stats ) {
16993  AssertionResult const& result = stats.assertionResult;
16994  if( !result.isOk() ) {
16995  std::string elementName;
16996  switch( result.getResultType() ) {
16997  case ResultWas::ThrewException:
16998  case ResultWas::FatalErrorCondition:
16999  elementName = "error";
17000  break;
17001  case ResultWas::ExplicitFailure:
17002  case ResultWas::ExpressionFailed:
17003  case ResultWas::DidntThrowException:
17004  elementName = "failure";
17005  break;
17006 
17007  // We should never see these here:
17008  case ResultWas::Info:
17009  case ResultWas::Warning:
17010  case ResultWas::Ok:
17011  case ResultWas::Unknown:
17012  case ResultWas::FailureBit:
17013  case ResultWas::Exception:
17014  elementName = "internalError";
17015  break;
17016  }
17017 
17018  XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17019 
17020  xml.writeAttribute( "message", result.getExpression() );
17021  xml.writeAttribute( "type", result.getTestMacroName() );
17022 
17024  if (stats.totals.assertions.total() > 0) {
17025  rss << "FAILED" << ":\n";
17026  if (result.hasExpression()) {
17027  rss << " ";
17028  rss << result.getExpressionInMacro();
17029  rss << '\n';
17030  }
17031  if (result.hasExpandedExpression()) {
17032  rss << "with expansion:\n";
17033  rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17034  }
17035  } else {
17036  rss << '\n';
17037  }
17038 
17039  if( !result.getMessage().empty() )
17040  rss << result.getMessage() << '\n';
17041  for( auto const& msg : stats.infoMessages )
17042  if( msg.type == ResultWas::Info )
17043  rss << msg.message << '\n';
17044 
17045  rss << "at " << result.getSourceInfo();
17046  xml.writeText( rss.str(), XmlFormatting::Newline );
17047  }
17048  }
17049 
17050  CATCH_REGISTER_REPORTER( "junit", JunitReporter )
17051 
17052 } // end namespace Catch
17053 // end catch_reporter_junit.cpp
17054 // start catch_reporter_listening.cpp
17055 
17056 #include <cassert>
17057 
17058 namespace Catch {
17059 
17060  ListeningReporter::ListeningReporter() {
17061  // We will assume that listeners will always want all assertions
17062  m_preferences.shouldReportAllAssertions = true;
17063  }
17064 
17065  void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17066  m_listeners.push_back( std::move( listener ) );
17067  }
17068 
17069  void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17070  assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17071  m_reporter = std::move( reporter );
17072  m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17073  }
17074 
17075  ReporterPreferences ListeningReporter::getPreferences() const {
17076  return m_preferences;
17077  }
17078 
17079  std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17080  return std::set<Verbosity>{ };
17081  }
17082 
17083  void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
17084  for ( auto const& listener : m_listeners ) {
17085  listener->noMatchingTestCases( spec );
17086  }
17087  m_reporter->noMatchingTestCases( spec );
17088  }
17089 
17090  void ListeningReporter::reportInvalidArguments(std::string const&arg){
17091  for ( auto const& listener : m_listeners ) {
17092  listener->reportInvalidArguments( arg );
17093  }
17094  m_reporter->reportInvalidArguments( arg );
17095  }
17096 
17097 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17098  void ListeningReporter::benchmarkPreparing( std::string const& name ) {
17099  for (auto const& listener : m_listeners) {
17100  listener->benchmarkPreparing(name);
17101  }
17102  m_reporter->benchmarkPreparing(name);
17103  }
17104  void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
17105  for ( auto const& listener : m_listeners ) {
17106  listener->benchmarkStarting( benchmarkInfo );
17107  }
17108  m_reporter->benchmarkStarting( benchmarkInfo );
17109  }
17110  void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
17111  for ( auto const& listener : m_listeners ) {
17112  listener->benchmarkEnded( benchmarkStats );
17113  }
17114  m_reporter->benchmarkEnded( benchmarkStats );
17115  }
17116 
17117  void ListeningReporter::benchmarkFailed( std::string const& error ) {
17118  for (auto const& listener : m_listeners) {
17119  listener->benchmarkFailed(error);
17120  }
17121  m_reporter->benchmarkFailed(error);
17122  }
17123 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17124 
17125  void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
17126  for ( auto const& listener : m_listeners ) {
17127  listener->testRunStarting( testRunInfo );
17128  }
17129  m_reporter->testRunStarting( testRunInfo );
17130  }
17131 
17132  void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17133  for ( auto const& listener : m_listeners ) {
17134  listener->testGroupStarting( groupInfo );
17135  }
17136  m_reporter->testGroupStarting( groupInfo );
17137  }
17138 
17139  void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17140  for ( auto const& listener : m_listeners ) {
17141  listener->testCaseStarting( testInfo );
17142  }
17143  m_reporter->testCaseStarting( testInfo );
17144  }
17145 
17146  void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17147  for ( auto const& listener : m_listeners ) {
17148  listener->sectionStarting( sectionInfo );
17149  }
17150  m_reporter->sectionStarting( sectionInfo );
17151  }
17152 
17153  void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
17154  for ( auto const& listener : m_listeners ) {
17155  listener->assertionStarting( assertionInfo );
17156  }
17157  m_reporter->assertionStarting( assertionInfo );
17158  }
17159 
17160  // The return value indicates if the messages buffer should be cleared:
17161  bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
17162  for( auto const& listener : m_listeners ) {
17163  static_cast<void>( listener->assertionEnded( assertionStats ) );
17164  }
17165  return m_reporter->assertionEnded( assertionStats );
17166  }
17167 
17168  void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
17169  for ( auto const& listener : m_listeners ) {
17170  listener->sectionEnded( sectionStats );
17171  }
17172  m_reporter->sectionEnded( sectionStats );
17173  }
17174 
17175  void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17176  for ( auto const& listener : m_listeners ) {
17177  listener->testCaseEnded( testCaseStats );
17178  }
17179  m_reporter->testCaseEnded( testCaseStats );
17180  }
17181 
17182  void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17183  for ( auto const& listener : m_listeners ) {
17184  listener->testGroupEnded( testGroupStats );
17185  }
17186  m_reporter->testGroupEnded( testGroupStats );
17187  }
17188 
17189  void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
17190  for ( auto const& listener : m_listeners ) {
17191  listener->testRunEnded( testRunStats );
17192  }
17193  m_reporter->testRunEnded( testRunStats );
17194  }
17195 
17196  void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
17197  for ( auto const& listener : m_listeners ) {
17198  listener->skipTest( testInfo );
17199  }
17200  m_reporter->skipTest( testInfo );
17201  }
17202 
17203  bool ListeningReporter::isMulti() const {
17204  return true;
17205  }
17206 
17207 } // end namespace Catch
17208 // end catch_reporter_listening.cpp
17209 // start catch_reporter_xml.cpp
17210 
17211 #if defined(_MSC_VER)
17212 #pragma warning(push)
17213 #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
17214  // Note that 4062 (not all labels are handled
17215  // and default is missing) is enabled
17216 #endif
17217 
17218 namespace Catch {
17219  XmlReporter::XmlReporter( ReporterConfig const& _config )
17220  : StreamingReporterBase( _config ),
17221  m_xml(_config.stream())
17222  {
17223  m_reporterPrefs.shouldRedirectStdOut = true;
17224  m_reporterPrefs.shouldReportAllAssertions = true;
17225  }
17226 
17227  XmlReporter::~XmlReporter() = default;
17228 
17229  std::string XmlReporter::getDescription() {
17230  return "Reports test results as an XML document";
17231  }
17232 
17233  std::string XmlReporter::getStylesheetRef() const {
17234  return std::string();
17235  }
17236 
17237  void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
17238  m_xml
17239  .writeAttribute( "filename", sourceInfo.file )
17240  .writeAttribute( "line", sourceInfo.line );
17241  }
17242 
17243  void XmlReporter::noMatchingTestCases( std::string const& s ) {
17244  StreamingReporterBase::noMatchingTestCases( s );
17245  }
17246 
17247  void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
17248  StreamingReporterBase::testRunStarting( testInfo );
17249  std::string stylesheetRef = getStylesheetRef();
17250  if( !stylesheetRef.empty() )
17251  m_xml.writeStylesheetRef( stylesheetRef );
17252  m_xml.startElement( "Catch" );
17253  if( !m_config->name().empty() )
17254  m_xml.writeAttribute( "name", m_config->name() );
17255  if (m_config->testSpec().hasFilters())
17256  m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
17257  if( m_config->rngSeed() != 0 )
17258  m_xml.scopedElement( "Randomness" )
17259  .writeAttribute( "seed", m_config->rngSeed() );
17260  }
17261 
17262  void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17263  StreamingReporterBase::testGroupStarting( groupInfo );
17264  m_xml.startElement( "Group" )
17265  .writeAttribute( "name", groupInfo.name );
17266  }
17267 
17268  void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17269  StreamingReporterBase::testCaseStarting(testInfo);
17270  m_xml.startElement( "TestCase" )
17271  .writeAttribute( "name", trim( testInfo.name ) )
17272  .writeAttribute( "description", testInfo.description )
17273  .writeAttribute( "tags", testInfo.tagsAsString() );
17274 
17275  writeSourceInfo( testInfo.lineInfo );
17276 
17277  if ( m_config->showDurations() == ShowDurations::Always )
17278  m_testCaseTimer.start();
17279  m_xml.ensureTagClosed();
17280  }
17281 
17282  void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17283  StreamingReporterBase::sectionStarting( sectionInfo );
17284  if( m_sectionDepth++ > 0 ) {
17285  m_xml.startElement( "Section" )
17286  .writeAttribute( "name", trim( sectionInfo.name ) );
17287  writeSourceInfo( sectionInfo.lineInfo );
17288  m_xml.ensureTagClosed();
17289  }
17290  }
17291 
17292  void XmlReporter::assertionStarting( AssertionInfo const& ) { }
17293 
17294  bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
17295 
17296  AssertionResult const& result = assertionStats.assertionResult;
17297 
17298  bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17299 
17300  if( includeResults || result.getResultType() == ResultWas::Warning ) {
17301  // Print any info messages in <Info> tags.
17302  for( auto const& msg : assertionStats.infoMessages ) {
17303  if( msg.type == ResultWas::Info && includeResults ) {
17304  m_xml.scopedElement( "Info" )
17305  .writeText( msg.message );
17306  } else if ( msg.type == ResultWas::Warning ) {
17307  m_xml.scopedElement( "Warning" )
17308  .writeText( msg.message );
17309  }
17310  }
17311  }
17312 
17313  // Drop out if result was successful but we're not printing them.
17314  if( !includeResults && result.getResultType() != ResultWas::Warning )
17315  return true;
17316 
17317  // Print the expression if there is one.
17318  if( result.hasExpression() ) {
17319  m_xml.startElement( "Expression" )
17320  .writeAttribute( "success", result.succeeded() )
17321  .writeAttribute( "type", result.getTestMacroName() );
17322 
17323  writeSourceInfo( result.getSourceInfo() );
17324 
17325  m_xml.scopedElement( "Original" )
17326  .writeText( result.getExpression() );
17327  m_xml.scopedElement( "Expanded" )
17328  .writeText( result.getExpandedExpression() );
17329  }
17330 
17331  // And... Print a result applicable to each result type.
17332  switch( result.getResultType() ) {
17333  case ResultWas::ThrewException:
17334  m_xml.startElement( "Exception" );
17335  writeSourceInfo( result.getSourceInfo() );
17336  m_xml.writeText( result.getMessage() );
17337  m_xml.endElement();
17338  break;
17339  case ResultWas::FatalErrorCondition:
17340  m_xml.startElement( "FatalErrorCondition" );
17341  writeSourceInfo( result.getSourceInfo() );
17342  m_xml.writeText( result.getMessage() );
17343  m_xml.endElement();
17344  break;
17345  case ResultWas::Info:
17346  m_xml.scopedElement( "Info" )
17347  .writeText( result.getMessage() );
17348  break;
17349  case ResultWas::Warning:
17350  // Warning will already have been written
17351  break;
17352  case ResultWas::ExplicitFailure:
17353  m_xml.startElement( "Failure" );
17354  writeSourceInfo( result.getSourceInfo() );
17355  m_xml.writeText( result.getMessage() );
17356  m_xml.endElement();
17357  break;
17358  default:
17359  break;
17360  }
17361 
17362  if( result.hasExpression() )
17363  m_xml.endElement();
17364 
17365  return true;
17366  }
17367 
17368  void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
17369  StreamingReporterBase::sectionEnded( sectionStats );
17370  if( --m_sectionDepth > 0 ) {
17371  XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
17372  e.writeAttribute( "successes", sectionStats.assertions.passed );
17373  e.writeAttribute( "failures", sectionStats.assertions.failed );
17374  e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
17375 
17376  if ( m_config->showDurations() == ShowDurations::Always )
17377  e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
17378 
17379  m_xml.endElement();
17380  }
17381  }
17382 
17383  void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17384  StreamingReporterBase::testCaseEnded( testCaseStats );
17385  XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
17386  e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
17387 
17388  if ( m_config->showDurations() == ShowDurations::Always )
17389  e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17390 
17391  if( !testCaseStats.stdOut.empty() )
17392  m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17393  if( !testCaseStats.stdErr.empty() )
17394  m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17395 
17396  m_xml.endElement();
17397  }
17398 
17399  void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17400  StreamingReporterBase::testGroupEnded( testGroupStats );
17401  // TODO: Check testGroupStats.aborting and act accordingly.
17402  m_xml.scopedElement( "OverallResults" )
17403  .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
17404  .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
17405  .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
17406  m_xml.scopedElement( "OverallResultsCases")
17407  .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
17408  .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
17409  .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
17410  m_xml.endElement();
17411  }
17412 
17413  void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
17414  StreamingReporterBase::testRunEnded( testRunStats );
17415  m_xml.scopedElement( "OverallResults" )
17416  .writeAttribute( "successes", testRunStats.totals.assertions.passed )
17417  .writeAttribute( "failures", testRunStats.totals.assertions.failed )
17418  .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
17419  m_xml.scopedElement( "OverallResultsCases")
17420  .writeAttribute( "successes", testRunStats.totals.testCases.passed )
17421  .writeAttribute( "failures", testRunStats.totals.testCases.failed )
17422  .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
17423  m_xml.endElement();
17424  }
17425 
17426 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17427  void XmlReporter::benchmarkPreparing(std::string const& name) {
17428  m_xml.startElement("BenchmarkResults")
17429  .writeAttribute("name", name);
17430  }
17431 
17432  void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
17433  m_xml.writeAttribute("samples", info.samples)
17434  .writeAttribute("resamples", info.resamples)
17435  .writeAttribute("iterations", info.iterations)
17436  .writeAttribute("clockResolution", info.clockResolution)
17437  .writeAttribute("estimatedDuration", info.estimatedDuration)
17438  .writeComment("All values in nano seconds");
17439  }
17440 
17441  void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17442  m_xml.startElement("mean")
17443  .writeAttribute("value", benchmarkStats.mean.point.count())
17444  .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17445  .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17446  .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17447  m_xml.endElement();
17448  m_xml.startElement("standardDeviation")
17449  .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17450  .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17451  .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17452  .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17453  m_xml.endElement();
17454  m_xml.startElement("outliers")
17455  .writeAttribute("variance", benchmarkStats.outlierVariance)
17456  .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17457  .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17458  .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17459  .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17460  m_xml.endElement();
17461  m_xml.endElement();
17462  }
17463 
17464  void XmlReporter::benchmarkFailed(std::string const &error) {
17465  m_xml.scopedElement("failed").
17466  writeAttribute("message", error);
17467  m_xml.endElement();
17468  }
17469 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17470 
17471  CATCH_REGISTER_REPORTER( "xml", XmlReporter )
17472 
17473 } // end namespace Catch
17474 
17475 #if defined(_MSC_VER)
17476 #pragma warning(pop)
17477 #endif
17478 // end catch_reporter_xml.cpp
17479 
17480 namespace Catch {
17481  LeakDetector leakDetector;
17482 }
17483 
17484 #ifdef __clang__
17485 #pragma clang diagnostic pop
17486 #endif
17487 
17488 // end catch_impl.hpp
17489 #endif
17490 
17491 #ifdef CATCH_CONFIG_MAIN
17492 // start catch_default_main.hpp
17493 
17494 #ifndef __OBJC__
17495 
17496 #if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17497 // Standard C/C++ Win32 Unicode wmain entry point
17498 extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
17499 #else
17500 // Standard C/C++ main entry point
17501 int main (int argc, char * argv[]) {
17502 #endif
17503 
17504  return Catch::Session().run( argc, argv );
17505 }
17506 
17507 #else // __OBJC__
17508 
17509 // Objective-C entry point
17510 int main (int argc, char * const argv[]) {
17511 #if !CATCH_ARC_ENABLED
17512  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17513 #endif
17514 
17515  Catch::registerTestMethods();
17516  int result = Catch::Session().run( argc, (char**)argv );
17517 
17518 #if !CATCH_ARC_ENABLED
17519  [pool drain];
17520 #endif
17521 
17522  return result;
17523 }
17524 
17525 #endif // __OBJC__
17526 
17527 // end catch_default_main.hpp
17528 #endif
17529 
17530 #if !defined(CATCH_CONFIG_IMPL_ONLY)
17531 
17532 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17533 # undef CLARA_CONFIG_MAIN
17534 #endif
17535 
17536 #if !defined(CATCH_CONFIG_DISABLE)
17537 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17539 #ifdef CATCH_CONFIG_PREFIX_ALL
17540 
17541 #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17542 #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17543 
17544 #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17545 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17546 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17547 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17548 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17549 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17550 #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17551 
17552 #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17553 #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17554 #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17555 #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17556 #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17557 
17558 #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17559 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17560 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17561 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17562 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17563 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17564 #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17565 
17566 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17567 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17568 
17569 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17570 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17571 
17572 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17573 #define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17574 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17575 #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17576 
17577 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17578 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17579 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17580 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17581 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17582 #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17583 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17584 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17585 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17586 
17587 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17588 
17589 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17590 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17591 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17592 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17593 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17594 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17595 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17596 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17597 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17598 #else
17599 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17600 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17601 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17602 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17603 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17604 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17605 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17606 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17607 #endif
17608 
17609 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17610 #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17611 #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17612 #else
17613 #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17614 #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17615 #endif
17616 
17617 // "BDD-style" convenience wrappers
17618 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17619 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17620 #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17621 #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17622 #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17623 #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17624 #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17625 #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17626 
17627 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17628 #define CATCH_BENCHMARK(...) \
17629  INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17630 #define CATCH_BENCHMARK_ADVANCED(name) \
17631  INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17632 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17633 
17634 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17635 #else
17636 
17637 #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17638 #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17639 
17640 #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17641 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17642 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17643 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17644 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17645 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17646 #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17647 
17648 #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17649 #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17650 #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17651 #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17652 #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17653 
17654 #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17655 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17656 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17657 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17658 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17659 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17660 #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17661 
17662 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17663 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17664 
17665 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17666 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17667 
17668 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17669 #define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17670 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17671 #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17672 
17673 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17674 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17675 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17676 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17677 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17678 #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17679 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17680 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17681 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17682 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17683 
17684 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17685 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17686 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17687 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17688 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17689 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17690 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17691 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17692 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17693 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17694 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17695 #else
17696 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17697 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17698 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17699 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17700 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17701 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17702 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17703 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17704 #define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17705 #define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17706 #endif
17707 
17708 #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17709 #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17710 #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17711 #else
17712 #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17713 #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17714 #endif
17715 
17716 #endif
17717 
17718 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17719 
17720 // "BDD-style" convenience wrappers
17721 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17722 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17723 
17724 #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17725 #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17726 #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17727 #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17728 #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17729 #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17730 
17731 #if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17732 #define BENCHMARK(...) \
17733  INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17734 #define BENCHMARK_ADVANCED(name) \
17735  INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____B_E_N_C_H____), name)
17736 #endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17737 
17738 using Catch::Detail::Approx;
17739 
17740 #else // CATCH_CONFIG_DISABLE
17741 
17743 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17744 #ifdef CATCH_CONFIG_PREFIX_ALL
17745 
17746 #define CATCH_REQUIRE( ... ) (void)(0)
17747 #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17748 
17749 #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17750 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17751 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17752 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17753 #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17754 #endif// CATCH_CONFIG_DISABLE_MATCHERS
17755 #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17756 
17757 #define CATCH_CHECK( ... ) (void)(0)
17758 #define CATCH_CHECK_FALSE( ... ) (void)(0)
17759 #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17760 #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17761 #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17762 
17763 #define CATCH_CHECK_THROWS( ... ) (void)(0)
17764 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17765 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17766 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17767 #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17768 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17769 #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17770 
17771 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17772 #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17773 
17774 #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17775 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17776 
17777 #define CATCH_INFO( msg ) (void)(0)
17778 #define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17779 #define CATCH_WARN( msg ) (void)(0)
17780 #define CATCH_CAPTURE( msg ) (void)(0)
17781 
17782 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17783 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17784 #define CATCH_METHOD_AS_TEST_CASE( method, ... )
17785 #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17786 #define CATCH_SECTION( ... )
17787 #define CATCH_DYNAMIC_SECTION( ... )
17788 #define CATCH_FAIL( ... ) (void)(0)
17789 #define CATCH_FAIL_CHECK( ... ) (void)(0)
17790 #define CATCH_SUCCEED( ... ) (void)(0)
17791 
17792 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17793 
17794 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17795 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17796 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17797 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17798 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17799 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17800 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17801 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17802 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17803 #else
17804 #define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17805 #define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17806 #define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17807 #define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17808 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17809 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17810 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17811 #define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17812 #endif
17813 
17814 // "BDD-style" convenience wrappers
17815 #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17816 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17817 #define CATCH_GIVEN( desc )
17818 #define CATCH_AND_GIVEN( desc )
17819 #define CATCH_WHEN( desc )
17820 #define CATCH_AND_WHEN( desc )
17821 #define CATCH_THEN( desc )
17822 #define CATCH_AND_THEN( desc )
17823 
17824 #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17825 #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17826 
17827 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17828 #else
17829 
17830 #define REQUIRE( ... ) (void)(0)
17831 #define REQUIRE_FALSE( ... ) (void)(0)
17832 
17833 #define REQUIRE_THROWS( ... ) (void)(0)
17834 #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17835 #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17836 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17837 #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17838 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17839 #define REQUIRE_NOTHROW( ... ) (void)(0)
17840 
17841 #define CHECK( ... ) (void)(0)
17842 #define CHECK_FALSE( ... ) (void)(0)
17843 #define CHECKED_IF( ... ) if (__VA_ARGS__)
17844 #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17845 #define CHECK_NOFAIL( ... ) (void)(0)
17846 
17847 #define CHECK_THROWS( ... ) (void)(0)
17848 #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17849 #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17850 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17851 #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17852 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17853 #define CHECK_NOTHROW( ... ) (void)(0)
17854 
17855 #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17856 #define CHECK_THAT( arg, matcher ) (void)(0)
17857 
17858 #define REQUIRE_THAT( arg, matcher ) (void)(0)
17859 #endif // CATCH_CONFIG_DISABLE_MATCHERS
17860 
17861 #define INFO( msg ) (void)(0)
17862 #define UNSCOPED_INFO( msg ) (void)(0)
17863 #define WARN( msg ) (void)(0)
17864 #define CAPTURE( msg ) (void)(0)
17865 
17866 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17867 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17868 #define METHOD_AS_TEST_CASE( method, ... )
17869 #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17870 #define SECTION( ... )
17871 #define DYNAMIC_SECTION( ... )
17872 #define FAIL( ... ) (void)(0)
17873 #define FAIL_CHECK( ... ) (void)(0)
17874 #define SUCCEED( ... ) (void)(0)
17875 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
17876 
17877 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17878 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17879 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17880 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17881 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17882 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17883 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17884 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17885 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17886 #else
17887 #define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17888 #define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17889 #define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17890 #define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17891 #define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17892 #define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17893 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17894 #define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17895 #endif
17896 
17897 #define STATIC_REQUIRE( ... ) (void)(0)
17898 #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17899 
17900 #endif
17901 
17902 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17903 
17904 // "BDD-style" convenience wrappers
17905 #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
17906 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
17907 
17908 #define GIVEN( desc )
17909 #define AND_GIVEN( desc )
17910 #define WHEN( desc )
17911 #define AND_WHEN( desc )
17912 #define THEN( desc )
17913 #define AND_THEN( desc )
17914 
17915 using Catch::Detail::Approx;
17916 
17917 #endif
17918 
17919 #endif // ! CATCH_CONFIG_IMPL_ONLY
17920 
17921 // start catch_reenable_warnings.h
17922 
17923 
17924 #ifdef __clang__
17925 # ifdef __ICC // icpc defines the __clang__ macro
17926 # pragma warning(pop)
17927 # else
17928 # pragma clang diagnostic pop
17929 # endif
17930 #elif defined __GNUC__
17931 # pragma GCC diagnostic pop
17932 #endif
17933 
17934 // end catch_reenable_warnings.h
17935 // end catch.hpp
17936 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
17937 
Definition: catch.hpp:3260
Definition: catch.hpp:2298
Definition: catch.hpp:4551
Definition: catch.hpp:3939
Definition: catch.hpp:4660
Definition: catch.hpp:1394
Definition: catch.hpp:4008
Definition: catch.hpp:2524
Definition: catch.hpp:2519
Definition: catch.hpp:484
Definition: catch.hpp:2222
Definition: catch.hpp:2974
Definition: catch.hpp:2614
int main(int argc, char **argv)
Definition: main.cpp:18
Definition: catch.hpp:547
Definition: catch.hpp:3857
Definition: catch.hpp:2546
Definition: catch.hpp:3984
Definition: catch.hpp:1613
Definition: catch.hpp:4118
Definition: catch.hpp:3965
Definition: catch.hpp:2650
Definition: catch.hpp:2456
Definition: catch.hpp:4496
Definition: pointer_wrapper.hpp:23
Definition: catch.hpp:98
Definition: sfinae_test.cpp:40
Definition: catch.hpp:3239
A non-owning string class (similar to the forthcoming std::string_view) Note that, because a StringRef may be a substring of another string, it may not be null terminated.
Definition: catch.hpp:604
Definition: catch.hpp:1375
Definition: catch.hpp:984
RangeType< double > Range
3.0.0 TODO: break reverse-compatibility by changing RangeType to Range.
Definition: range.hpp:19
Definition: catch.hpp:3013
Definition: catch.hpp:3238
Definition: catch.hpp:2892
Definition: catch.hpp:2541
Definition: catch.hpp:4058
Definition: catch.hpp:960
Definition: catch.hpp:926
Definition: catch.hpp:532
Definition: catch.hpp:2874
Definition: catch.hpp:4290
Definition: catch.hpp:3237
Definition: catch.hpp:923
Definition: catch.hpp:4491
Definition: catch.hpp:2336
Definition: catch.hpp:578
Definition: catch.hpp:2840
Definition: catch.hpp:4154
Definition: catch.hpp:3951
Definition: catch.hpp:2963
Definition: catch.hpp:4475
Definition: catch.hpp:500
Definition: catch.hpp:3656
Definition: catch.hpp:4402
Definition: catch.hpp:1431
Definition: catch.hpp:3008
Definition: catch.hpp:1464
Definition: catch.hpp:489
Definition: catch.hpp:3679
Definition: catch.hpp:1438
Definition: catch.hpp:2909
Definition: catch.hpp:4481
Definition: catch.hpp:4505
Definition: catch.hpp:4833
Definition: catch.hpp:3278
Definition: catch.hpp:3536
Definition: catch.hpp:934
Definition: catch.hpp:4705
Definition: catch.hpp:3768
Definition: catch.hpp:1351
Definition: catch.hpp:4486
Definition: catch.hpp:4765
Definition: catch.hpp:3917
Definition: catch.hpp:1474
Definition: catch.hpp:570
Definition: catch.hpp:952
Definition: catch.hpp:2200
Definition: catch.hpp:4800
Definition: catch.hpp:4249
Definition: catch.hpp:4193
Definition: catch.hpp:2858
Definition: catch.hpp:3843
Definition: catch.hpp:2597
Definition: catch.hpp:2005
Definition: catch.hpp:978
Definition: catch.hpp:3076
Definition: catch.hpp:3214
Definition: catch.hpp:4360
Definition: catch.hpp:2625
Definition: catch.hpp:1562
Definition: catch.hpp:1996
Definition: catch.hpp:479
Definition: catch.hpp:1991
Definition: catch.hpp:2412
Definition: catch.hpp:3019
Definition: catch.hpp:2827
Definition: catch.hpp:4351
Definition: catch.hpp:2639
Definition: catch.hpp:925